﻿
namespace n_ImagePanel
{
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

using System.Diagnostics;
using c_ControlType;
using c_MyObjectSet;
using n_EventLink;
using n_GUIcoder;
using n_GUIset;
using n_MainSystemData;
using n_GVar;
using n_HardModule;
using n_Head;
using n_MyControl;
using n_MyFileObject;
using n_MyObject;
using n_MyObjectList;
using n_OS;
using n_SelectPanel;
using n_Shape;
using n_StartTip;
using n_UIModule;
using n_GNote;
using n_EnginePair;
using n_SG;
using n_GUICommon;
using n_ObjectMesPanel;
using n_MidPortList;
using n_LineColorBox;
using n_SwitchTip;
using n_GroupList;
using n_CLineList;
using n_EPanel;

//*****************************************************
//图形编辑器容器类
public class ImagePanel : Panel
{
	public delegate void D_ExtOpenFile( string filename );
	public static D_ExtOpenFile ExtOpenFile;
	
	public delegate void D_Tick( object sender, EventArgs e );
	public static D_Tick dTick;
	
	//===========================================
	//起始提示控件
	public StartTip STip;
	public SwitchTip SWTip;
	//事件链接列表
	public EventLink EL;
	//选中面板
	public SelectPanel SelPanel;
	//组件列表
	public MyObjectList myModuleList;
	//标题栏部分
	public Head GHead;
	//垃圾桶
	public Recycler myRecycler;
	//导线颜色指示器
	public LineColorBox myLineColorBox;
	//过渡点列表
	public MidPortList myMidPortList;
	
	//电路线列表
	public CLineList myCLineList;
	
	//分组列表
	public GroupList mGroupList;
	
	//指令提示信息列表
	public ObjectMesPanel[] ObjectMesPanelList;
	
	//指令编辑面板
	EPanel ePanel;
	
	//组件库
	//public MyModuleLibPanel myModuleLib;
	//===========================================
	
	public static bool IgnoreTextChanged;
	
	//是否为调试模式 显示各个元素的内部名字
	public static bool DebugMode = false;
	
	public static int RHidWidth;
	public static int RShowX;
	public static int MaxRShowX;
	static bool RisShow;
	
	//软件加速器
	public int voffset;
	
	//事件池数目
	public int EventNumber;
	public const int DefaultEventNumber = 8;
	public const int StartNeedNumber = 0; //可能是用于初始化时候给Init函数准备的堆栈空间
	
	//针对Arduino是否进行内存节省的标志
	public int RAM_Save;
	public const int RAM_Save_Start = 2;
	
	//VEX引擎驱动周期
	public int VEX_Tick;
	
	//禁用碰撞效果
	public bool DisableHit;
	
	//隐藏界面导线 0:显示 1:隐藏
	public int HideLine;
	
	//是否隐藏所有模块的名字
	public bool HideName;
	
	public string tempGroupMes;
	
	//自定义操作系统路径
	public string OSPath;
	
	//窗体宽度和高度
	public static int FormWidth;
	public static int FormHeight;
	
	//系统信息
	public const string SYSHEAD_DownloadMes = "download:";
	public string SysMes;
	
	public string UserMes;
	
	//这个参数控制是否显示扩展信息
	const bool ShowExtendItem = true;
	
	//XY为虚拟地图的原点相对于屏幕左上角的位置, 也就是如果在世界原点位置显示一个点, 正好在屏幕坐标 (SX,SY) 
	public int StartX, StartY;
	float modX;
	float modY;
	
	//尺寸改变时自动让图像居中
	int OldW;
	int OldH;
	
	public bool isMousePress;
	int Last_mX, Last_mY;
	
	Cursor CursorMove;
	Cursor CursorEdit;
	
	int MouseX;
	int MouseY;
	
	Brush RFBrush;
	Pen RDPen;
	
	Pen p0;
	int a0;
	
	Pen pb1;
	Pen p1;
	int a1;
	
	Pen pb2;
	Pen p2;
	int a2;
	
	static Brush PyVarBackBrush;
	static Pen HistoryPen;
	
	Pen AreaPen;
	
	Font WarningFont;
	
	Font NumberFont;
	
	static Timer ChangeDetectTimer;
	
	static Timer FlashTimer;
	public static bool Flash;
	
	public bool MultSelect;
	
	public bool isNoModule;
	
	public static MyObject NewObject;
	static Timer MoveTimer;
	int CenterX;
	int CenterY;
	int LastCenterX;
	int LastCenterY;
	
	int ErrorTimes;
	
	public static int ScaleIndex;
	public static int[] ScaleList;
	public static int AScale;
	public const int AScaleMid = 1024;
	public static int tempAScale;
	
	public static int RefreshTick;
	
	public static int MoveTick;
	public const int MaxMoveTick = 5;
	
	public Keys CKeys;
	
	int[] HistoryScaleList;
	Point[] HistoryPointList;
	string[] HistoryList;
	int UndoStart;
	int UndoNext;
	int UndoEnd;
	
	public bool HaseShow;
	bool TranslateAsked;
	
	//设置是否跳过刷新
	public bool SkipRefresh;
	
	public bool MultEageShow;
	
	float MinX;
	float MaxX;
	float MinY;
	float MaxY;
	
	public bool Pause;
	
	public static bool ShowMessage;
	
	//是否载入中 (暂停文本改变检测)
	public static bool isLoading;
	
	//========================================================
	
	static Brush ShowMesBackBrush;
	static Brush ShowStartBackBrush;
	
	static Brush ShowInsBackBrush;
	
	//public static int UIMode = UIMode_Standard;
	//public const int UIMode_Simple = 0;
	//public const int UIMode_Standard = 1;
	
	static GraphicsPath MesPath;
	
	public static Bitmap LineMap;
	public static Graphics gl;
	
	static Bitmap downloadok;
	static Bitmap downloadwarning;
	static Bitmap downloaderror;
	
	//===========================================
	
	static float MesY1;
	static float MesY2;
	static float MesY3;
	
	static SolidBrush MesBrush1;
	static SolidBrush MesBrush2;
	static SolidBrush MesBrush3;
	
	static Bitmap ImgMes1;
	static Bitmap ImgMes2;
	static Bitmap ImgMes3;
	
	//===========================================
	//可用于后续升级为直接编辑参数
	public static TextBox MyTextBox;
	
	
	//初始化
	public static void Init()
	{
		MyTextBox = new TextBox();
		MyTextBox.Visible = true;
		MyTextBox.Font = GUIset.Font12;
		MyTextBox.Width = 200;
		MyTextBox.BorderStyle = BorderStyle.None;
		MyTextBox.AutoSize = false;
		MyTextBox.Location = new Point( 300, 300 );
		MyTextBox.Visible = false;
		
		PyVarBackBrush = new SolidBrush( Color.FromArgb( 150, 215, 235, 255 ) );
		
		//ShowStartBackBrush = new SolidBrush( Color.FromArgb( 180, 50, 50, 50 ) );
		//ShowStartBackBrush = new SolidBrush( Color.FromArgb( 200, 36, 38, 53 ) );
		ShowStartBackBrush = new SolidBrush( Color.FromArgb( 240, 240, 240, 240 ) );
		
		
		ShowMesBackBrush = new SolidBrush( Color.FromArgb( 200, 50, 50, 50 ) );
		ShowInsBackBrush = new SolidBrush( Color.FromArgb( 150, 50, 50, 50 ) );
		
		HistoryPen = new Pen( Color.Gainsboro, 32 );
		HistoryPen.StartCap = LineCap.Round;
		HistoryPen.EndCap = LineCap.Round;
		
		//连线图 - 这里必须要创建最大屏幕尺寸的图片
		LineMap = new Bitmap( Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height );
		gl = Graphics.FromImage( LineMap );
		gl.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
		gl.Clear( Color.White );
		
		int h = 26;
		Point point1 = new Point( 461 + Head.ButtonNumber * Head.XO, 32 );
		Point point2 = new Point( 680 + Head.ButtonNumber * Head.XO, 32 );
		Point point3 = new Point( 680 + Head.ButtonNumber * Head.XO - h, 32 + h );
		Point point4 = new Point( 461 + Head.ButtonNumber * Head.XO - h, 32 + h );
		Point[] pntArr = { point1, point2, point3, point4 };
		
		MesPath = new GraphicsPath();
		MesPath.Reset();
		MesPath.AddPolygon( pntArr );
		
		RHidWidth = SystemData.RightBarValue;
		RShowX = RHidWidth;
		
		if( n_Language.Language.isChinese ) {
			MaxRShowX = 110;
		}
		else {
			MaxRShowX = 125;
		}
		
		RisShow = false;
		
		ShowMessage = true;
		
		ScaleList = new int[21];
		
		float f1 = 100;
		float f2 = 100;
		float ff = 0.8f;
		
		ScaleList[10] = AScaleMid * 100 / 100;
		
		f1 *= ff;
		f2 /= ff;
		ScaleList[9] = AScaleMid * (int)f1 / 100;
		ScaleList[11] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[8] = AScaleMid * (int)f1 / 100;
		ScaleList[12] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[7] = AScaleMid * (int)f1 / 100;
		ScaleList[13] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[6] = AScaleMid * (int)f1 / 100;
		ScaleList[14] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[5] = AScaleMid * (int)f1 / 100;
		ScaleList[15] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[4] = AScaleMid * (int)f1 / 100;
		ScaleList[16] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[3] = AScaleMid * (int)f1 / 100;
		ScaleList[17] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[2] = AScaleMid * (int)f1 / 100;
		ScaleList[18] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[1] = AScaleMid * (int)f1 / 100;
		ScaleList[19] = AScaleMid * (int)f2 / 100;
		f1 *= ff;
		f2 /= ff;
		ScaleList[0] = AScaleMid * (int)f1 / 100;
		ScaleList[20] = AScaleMid * (int)f2 / 100;
		
		n_Head.Head.Init();
		
		PortPenList.Init();
		
		n_MyIns.MyIns.Init();
		
		n_SimCommon.SimCommon.Init();
		
		n_PyVM.PyVM.Init();
		n_CCEngine.CCEngine.Init();
		
		downloadok = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "GFormControls" + OS.PATH_S + "ok.png" );
		downloadwarning = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "GFormControls" + OS.PATH_S + "warning.png" );
		downloaderror = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "GFormControls" + OS.PATH_S + "error.png" );
		
		//------------------------------------------------------------------
		
		ImgMes1 = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "mes-ui" + OS.PATH_S + "1.png" );
		ImgMes2 = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "mes-ui" + OS.PATH_S + "2.png" );
		ImgMes3 = new Bitmap( OS.SystemRoot + "Resource" + OS.PATH_S + "gui" + OS.PATH_S + "mes-ui" + OS.PATH_S + "3.png" );
		MesBrush1 = new SolidBrush( Color.FromArgb( 240, 240, 240 ) );
		MesBrush2 = new SolidBrush( Color.FromArgb( 230, 230, 230 ) );
		MesBrush3 = new SolidBrush( Color.FromArgb( 220, 220, 220 ) );
		MesY1 = 0;
		MesY2 = 0;
		MesY3 = 0;
		
		CLineList.Init();
		n_GNote.GNote.Init();
		n_HardModule.HardModule.Init();
		n_HardModule.Port.Init();
		n_GVar.GVar.Init();
		
		GroupList.Init();
		MyObject.Init1();
		
		//添加闪烁定时器
		FlashTimer = new Timer();
		FlashTimer.Interval = 500;
		FlashTimer.Enabled = false;
		Flash = false;
		
		//添加移动定时器
		MoveTimer = new Timer();
		MoveTimer.Interval = 50;
		MoveTimer.Enabled = false;
		
		//修改检测定时器
		ChangeDetectTimer = new Timer();
		ChangeDetectTimer.Interval = 500;
		ChangeDetectTimer.Enabled = false;
		
		//SetHotKeyMes();
	}
	
	//复位缩放
	static void ResetScale()
	{
		AScale = AScaleMid;
		tempAScale = AScale;
		ScaleIndex = 10;
	}
	
	//构造函数
	public ImagePanel( int Width, int Height ) : base()
	{
		this.BorderStyle = BorderStyle.None;
		this.BackColor = Color.Black;
		
		SetStyle(ControlStyles.UserPaint |
		         ControlStyles.AllPaintingInWmPaint |
		         ControlStyles.OptimizedDoubleBuffer |
		         ControlStyles.ResizeRedraw |
		         ControlStyles.SupportsTransparentBackColor,true);
		
		this.Dock = DockStyle.Fill;
		this.ImeMode = ImeMode.NoControl;
		SetSize( Width, Height );
		
		//可能用来设置输入法
		//ImeMode = ImeMode.On;
		
		Controls.Add( MyTextBox );
		
		ResetScale();
		
		isLoading = true;
		
		SkipRefresh = false;
		
		HaseShow = false;
		TranslateAsked = false;
		
		MultEageShow = true;
		
		TakeMoIndex = -1;
		TakePoIndex = -1;
		CLineIndex = -1;
		
		int MaxHistoryLength = 500;
		HistoryScaleList = new int[MaxHistoryLength];
		HistoryPointList = new Point[MaxHistoryLength];
		HistoryList = new string[MaxHistoryLength];
		UndoStart = 0;
		UndoNext = 0;
		UndoEnd = 0;
		
		ErrorTimes = 0;
		isNoModule = false;
		OSPath = null;
		
		SysMes = null;
		UserMes = null;
		
		CKeys = Keys.None;
		
		SG.Init();
		SG.Running = false;
		
		MultSelect = false;
		HideName = false;
		
		//添加刷新定时器
		FlashTimer.Tick += new EventHandler( FlashTimerTick );
		FlashTimer.Enabled = true;
		Flash = false;
		
		//添加移动定时器
		MoveTimer.Tick += new EventHandler( GPanel_Move );
		MoveTimer.Enabled = false;
		
		//修改检测定时器
		ChangeDetectTimer.Tick += new EventHandler( TextChangedDetect );
		ChangeDetectTimer.Enabled = true;
		
		CenterX = 0;
		CenterY = 0;
		LastCenterX = 0;
		LastCenterY = 0;
		NewObject = null;
		
		MouseX = 0;
		MouseY = 0;
		
		CursorEdit = new Cursor( OS.SystemRoot + "Resource" + OS.PATH_S + "myPointEdit.cur" );
		CursorMove = new Cursor( OS.SystemRoot + "Resource" + OS.PATH_S + "myPointMove.cur" );
		CursorMove = this.Cursor;
		this.Cursor = CursorMove;
		
		IgnoreTextChanged = false;
		
		RAM_Save = 0;
		voffset = 0;
		VEX_Tick = 10;
		DisableHit = false;
		HideLine = 0;
		
		StartX = Width / 2;
		StartY = Height / 2;
		
		isMousePress = false;
		Last_mX = 0;
		Last_mY = 0;
		
		this.MouseMove += new MouseEventHandler( UserMouseMove );
		this.MouseUp += new MouseEventHandler( UserMouseUp );
		this.MouseDown += new MouseEventHandler( UserMouseDown );
		this.MouseWheel += new MouseEventHandler( UserMouseWheel );
		this.DoubleClick += new EventHandler( UserMouseDClick );
		
		this.KeyDown += new KeyEventHandler( UserkeyDown );
		this.KeyUp += new KeyEventHandler( UserkeyUp );
		this.KeyPress += new KeyPressEventHandler( UserkeyPress );
		
		this.MouseLeave += new EventHandler(ImagePanel_MouseLeave);
		this.MouseEnter += new EventHandler(ImagePanel_MouseEnter);
		
		this.SizeChanged += new EventHandler( ImagePanel_SizeChanged );
		
		HardModule.ScaleChanged = null;
		myMidPortList = new MidPortList();
		myCLineList = new CLineList( this );
		myModuleList = new MyObjectList( this );
		SelPanel = new SelectPanel( myModuleList );
		mGroupList = new GroupList();
		EL = new EventLink( this.myModuleList, mGroupList );
		
		GHead = new Head( myModuleList );
		STip = new StartTip( myModuleList );
		SWTip = new SwitchTip();
		myRecycler = new Recycler();
		myLineColorBox = new LineColorBox();
		
		
		myModuleList.ClearModule = G.SimBox.SPanel.Clear;
		myModuleList.AddModule = G.SimBox.SPanel.Add;
		
		ObjectMesPanelList = new ObjectMesPanel[10];
		for( int i = 0; i < ObjectMesPanelList.Length; ++i ) {
			ObjectMesPanelList[i] = new ObjectMesPanel( i );
		}
		
		GHead.DeleScale = this.UserScale;
		
		n_ModuleLibPanel.MyModuleLibPanel.myModuleSelect = new n_ModuleLibPanel.MyModuleLibPanel.myModuleSelectEventHandler( AddNewModule );
		EnginePair.myModuleSelect = new EnginePair.myModuleSelectEventHandler( AddNewModule );
		
		RFBrush = new SolidBrush( Color.FromArgb( 85, 0, 0, 64 ) );
		RDPen = new Pen( Color.FromArgb(128, 128, 255) );
		
		p0 = new Pen( Color.WhiteSmoke, 2 );
		p0.StartCap = LineCap.Round;
		p0.EndCap = LineCap.Round;
		a0 = 0;
		
		pb1 = new Pen( Color.FromArgb(80, 120, 150), 3 );
		p1 = new Pen( Color.LightBlue, 1 );
		p1.StartCap = LineCap.Round;
		p1.EndCap = LineCap.Round;
		a1 = 0;
		
		pb2 = new Pen( Color.FromArgb(150, 120, 80), 3 );
		p2 = new Pen( Color.Yellow, 1 );
		p2.StartCap = LineCap.Round;
		p2.EndCap = LineCap.Round;
		a2 = 0;
		
		if( SystemData.isBlack ) {
			AreaPen = new Pen( Color.LightGray );
		}
		else {
			AreaPen = new Pen( Color.SlateGray );
		}
		AreaPen.DashStyle = DashStyle.Dash;
		AreaPen.DashPattern = new float[] { 10, 10 };
		
		NumberFont = new Font( "arial", 10 );
		
		WarningFont = new Font( "微软雅黑", 12 );
		
		Pause = false;
		
		
		ePanel = G.commonEXPBox.ePanel;
		ePanel.Location = new Point( (Width-ePanel.Width)/2, (Height-ePanel.Height)/2 );
		G.commonEXPBox.ePanel.Visible = false;
		Controls.Add( G.commonEXPBox.ePanel );
	}
	
	//设置尺寸
	public void SetSize( int w, int h )
	{
		this.Width = w;
		this.Height = h;
		OldW = w;
		OldH = h;
	}
	
	//关闭
	public void Close()
	{
		Controls.Remove( MyTextBox );
		
		FlashTimer.Tick -= new EventHandler( FlashTimerTick );
		FlashTimer.Enabled = false;
		
		MoveTimer.Tick -= new EventHandler( GPanel_Move );
		MoveTimer.Enabled = false;
		
		ChangeDetectTimer.Tick -= new EventHandler( TextChangedDetect );
		ChangeDetectTimer.Enabled = false;
	}
	
	//触发绘制 - 设置为 true 可以触发一次刷新
	public bool EnableOnceRefresh = false;
	public void MyRefresh()
	{
		if( G.SimulateMode && G.SimBox.isAct ) {
			if( !EnableOnceRefresh ) {
				return;
			}
			EnableOnceRefresh = false;
		}
		if( dTick != null ) {
			dTick( null, null );
		}
		Invalidate();
	}
	
	//触发绘制
	public void MyRefresh( Rectangle r )
	{
		//if( G.SimulateMode && SkipRefresh ) return;
		
		Invalidate( r );
	}
	
	//结束下载
	public void EndDownLoad()
	{
		GHead.isCompile = false;
		GHead.isDownLoad = false;
		
		Invalidate();
	}
	
	//更新图形界面参数
	public string VarToText()
	{
		return GUIcoder.VarToText( this );
	}
	
	//装载模块列表
	public void LoadModule( string GUItext, bool ShowMes )
	{
		try {
			myModuleList.Clear();
			EL.Clear();
			myMidPortList = new MidPortList();
			myCLineList = new CLineList( this );
			myModuleList.ShowStartMes = ShowMes;
			GUIcoder.TextToVar( this, myModuleList, myMidPortList, GUItext );
			
			RefreshLinePortName();
			
			//需要重新刷新,因为需要计算力矢量,因为力矢量需要计算两次,所以需要刷新两次
			//调用 GPanel_Refresh 会关闭定时器,所以需要重新打开定时器
			//myModuleList.DrawImage( g, this.StartX, this.StartY );
			//GPanel_Refresh( null, null );
			//RefreshTimer.Enabled = true;
			/*
			if( G.FlashBox.GetMessage() != null ) {
				try {
					this.Close();
				}
				catch {}
				G.SystemError( G.ccode.PathAndName, G.FlashBox.GetMessage() );
			}
			*/
		}
		catch(Exception e) {
			try {
				this.Close();
			}
			catch {}
			G.SystemError( G.ccode.PathAndName, e.ToString() );
		}
	}
	
	//检测程序语言
	public void AutoSetTableLanguage()
	{
		if( myModuleList.Language == null ) {
			myModuleList.Language = SystemData.ModuleLanguage;
		}
	}
	
	//翻译到英文
	public void Translate()
	{
		myModuleList.Language = n_MainSystemData.SystemData.ModuleLanguage;
		
		foreach( n_MyObject.MyObject m in myModuleList ) {
			if( !(m is n_MyFileObject.MyFileObject) ) {
				continue;
			}
			n_MyFileObject.MyFileObject mf = (n_MyFileObject.MyFileObject)m;
			
			string OldName = mf.Name;
			
			string NewName = mf.NameList[ 2 ];
			NewName = n_GUICommon.GUICommon.SearchName( this, NewName );
			
			RenameModule( mf, false, OldName, NewName );
			
			mf.Language = n_Language.Language.Mod_c;
			mf.Name = NewName;
			
			//修改事件列表
			for( int ei = 0; ei < mf.EventList.Length; ++ei ) {
				string EventEntry = mf.EventList[ ei ][ 0 ];
				if( EventEntry == "" ) {
					continue;
				}
				string OldEvemtMes = mf.EventList[ ei ][ 0 ];
				n_EventIns.EventIns ee = EL.GetEvent( mf, OldEvemtMes );
				
				mf.EventList[ ei ][ 0 ] = mf.Name + "_" + mf.EventList[ ei ][ mf.GetLC() ];
				if( ee != null ) {
					ee.EventEntry = mf.EventList[ ei ][ 0 ];
				}
			}
		}
		
		n_EXP.EXP.Translate = true;
	}
	
	//封包
	public void Pack( string HidMes )
	{
		myModuleList.Pack( HidMes );
	}
	
	//解封
	public void UnPack()
	{
		myModuleList.UnPack();
	}
	
	//添加一个信息面板指向输入的对象
	public void AddMesPanel( string Mes, int Level, MyObject target )
	{
		ObjectMesPanel im = ObjectMesPanelList[0];
		int ci = 0;
		for( int ii = 0; ii < ObjectMesPanelList.Length; ++ii ) {
			if( !ObjectMesPanelList[ii].Visible ) {
				im = ObjectMesPanelList[ii];
				ci = ii;
				break;
			}
		}
		//清除其他指向同一指令的显示栏
		for( int ii = 0; ii < ObjectMesPanelList.Length; ++ii ) {
			if( ObjectMesPanelList[ii].Visible && ObjectMesPanelList[ii].TargetIns == target && ii != ci ) {
				ObjectMesPanelList[ii].Visible = false;
			}
		}
		im.TargetIns = target;
		im.Mes = Mes;
		im.WarningLeavel = Level;
		im.AnyClickHide = !myModuleList.ShowMessage;
		im.ClickNumber = 0;
		im.Visible = true;
	}
	
	//重命名模块元素
	public void RenameModule( MyObject Owner, bool Var, string OldName, string NewName )
	{
		if( NewName.IndexOf( ' ' ) != -1 || NewName.IndexOf( '\t' ) != -1 ) {
			n_Debug.Warning.WarningMessage = "模块名称中出现了空格或者制表符: " + NewName;
			return;
		}
		
		//替换表达式里的模块
		foreach( MyObject mo in myModuleList ) {
			
			if( Owner.GroupMes != mo.GroupMes ) {
				continue;
			}
			
			if( (mo is n_FuncIns.FuncIns ) ) {
				n_FuncIns.FuncIns fi = (n_FuncIns.FuncIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
			if( (mo is n_IfElseIns.IfElseIns ) ) {
				n_IfElseIns.IfElseIns fi = (n_IfElseIns.IfElseIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
			if( (mo is n_LoopIns.LoopIns ) ) {
				n_LoopIns.LoopIns fi = (n_LoopIns.LoopIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
			if( (mo is n_ExtIns.ExtIns ) ) {
				n_ExtIns.ExtIns fi = (n_ExtIns.ExtIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
			if( (mo is n_WhileIns.WhileIns ) ) {
				n_WhileIns.WhileIns fi = (n_WhileIns.WhileIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
			if( (mo is n_WaitIns.WaitIns ) ) {
				n_WaitIns.WaitIns fi = (n_WaitIns.WaitIns)mo;
				RenameExp( Var, fi.MyEXP, OldName, NewName );
			}
		}
		G.SimBox.SPanel.RefreshNameList();
	}
	
	//给一个表达式里的名字重命名
	void RenameExp( bool Var, n_EXP.EXP MyEXP, string OldName, string NewName )
	{
		bool Changed = false;
		for( int j = 0; j < MyEXP.ExpTree.Length; ++j ) {
			if( MyEXP.ExpTree[j] == null ) {
				break;
			}
			n_EXP.EXP.ENote en = MyEXP.ExpTree[j];
			
			if( Var ) {
				if( en.WordList.Length == 3 && en.WordList[2] == OldName && (en.WordList[1] == n_EXP.EXP.ENote.t_WORD || en.WordList[1] == n_EXP.EXP.ENote.t_VAR ) ) {
					en.WordList[2] = NewName;
					Changed = true;
				}
			}
			else {
				if( en.WordList.Length > 3 && (en.WordList[1] == n_EXP.EXP.ENote.t_MFUNC || en.WordList[1] == n_EXP.EXP.ENote.t_MVAR) && en.WordList[2] == OldName ) {
					en.WordList[2] = NewName;
					Changed = true;
				}
				if( en.WordList.Length >= 3 && en.WordList[0] == n_EXP.EXP.ENote.v_Module && en.WordList[2] == OldName ) {
					en.WordList[2] = NewName;
					Changed = true;
				}
			}
		}
		if( Changed ) {
			MyEXP.RefreshRename();
		}
	}
	
	//定时运行
	public void GPanel_Move( object sender, EventArgs e )
	{
		int TargetX = -( LastCenterX - this.Width/2 );
		int TargetY = -( LastCenterY - this.Height/2 );
		if( NewObject != null && StartX <= TargetX ) {
			StartX += (TargetX - StartX) / 10 + 1;
			StartY += (TargetY - StartY) / 10 + 1;
			
			GHead.MouseMove( MouseX, MouseY );
			myModuleList.UserMouseMove( MouseX - StartX, MouseY - StartY );
			SelPanel.MouseMove( MouseX - StartX, MouseY - StartY );
			//MyModuleLibPanel.UserMouseMove( MouseX, MouseY );
			
			Invalidate();
			
			MoveTimer.Enabled = false;
		}
		else {
			MoveTimer.Enabled = false;
			NewObject = null;
		}
	}
	
	//文本改变检测
	void TextChangedDetect( object sender, EventArgs e )
	{
		if( G.SimulateMode ) {
			return;
		}
		if( !isLoading && !G.ccode.isChanged && G.ccode.GUItext != VarToText() ) {
			G.ccode.isChanged = true;
		}
	}
	
	bool isOK;
	
	public void RefreshLinePortName()
	{
		ClearLinePortName();
		
		//先更新Master端口
		int LoopTime1 = 0;
		do {
			isOK = true;
			RefreshLinePortNameOnceMaster();
			LoopTime1++;
		}
		while( !isOK && LoopTime1 < 100 );
		
		//再更新Client端口
		int LoopTime2 = 0;
		do {
			isOK = true;
			RefreshLinePortNameOnceClient();
			LoopTime2++;
		}
		while( !isOK && LoopTime2 < 100 );
		
		if( LoopTime1 >= 100 || LoopTime2 >= 100 ) {
			MessageBox.Show( "设置端口属性时循环次数过多, 可能是由于软件本身问题或者您的端口连接过多" );
		}
	}
	
	void ClearLinePortName()
	{
		foreach( MyObject mo in myModuleList ) {
			if( !(mo is HardModule) ) {
				continue;
			}
			HardModule hm = (HardModule)mo;
			for( int n = 0; n < hm.PORTList.Length; ++n ) {
				Port cp = hm.PORTList[n];
				cp.isDeal = false;
				if( cp.CanChange ) {
					cp.FuncName = PortFuncName.LINE;
					cp.ClientType = PortClientType.CLIENT;
				}
			}
		}
	}
	
	void RefreshLinePortNameOnceMaster()
	{
		foreach( MyObject mo in myModuleList ) {
			if( !(mo is HardModule) ) {
				continue;
			}
			HardModule hm = (HardModule)mo;
			for( int n = 0; n < hm.PORTList.Length; ++n ) {
				Port cp = hm.PORTList[n];
				if( cp.CanChange ) {
					if( cp.TargetPort != null && cp.ClientType != PortClientType.CLIENT ) {
						cp.ClientType = PortClientType.CLIENT;
					}
				}
				if( cp.isDeal ) {
					continue;
				}
				if( cp.ClientType != PortClientType.CLIENT ) {
					continue;
				}
				//当前端口为Line端口
				if( cp.CanChange && cp.TargetPort != null && cp.TargetPort.ClientType == PortClientType.MASTER ) {
					
					cp.isDeal = true;
					isOK = false;
					
					//把提取属性扩散到当前模块的其他同名端口上, 根据是否有链接对象设置为 MASTER 或 CLIENT
					for( int m = 0; m < hm.PORTList.Length; ++m ) {
						Port tcp = hm.PORTList[m];
						if( tcp.Name == cp.Name ) {
							if( tcp == cp ) {
								tcp.ClientType = PortClientType.CLIENT;
							}
							else {
								tcp.ClientType = PortClientType.MASTER;
								
								if( hm.ImageName == SPMoudleName.SYS_iport && cp.TargetPort != null ) {
									//tcp.Name = cp.TargetPort.Name;
									//cp.Name = cp.TargetPort.Name;
									tcp.TempName = cp.TargetPort.Name;
									cp.TempName = cp.TargetPort.Name;
								}
							}
							tcp.FuncName = cp.TargetPort.FuncName;
						}
						SwapPort( tcp );
					}
				}
			}
		}
	}
	
	//交换一个两个端口的连接方向
	void SwapPort( Port tcp )
	{
		//判断端口是否反接, 是的话就调整回来
		if( tcp.ClientType == PortClientType.MASTER && tcp.TargetPort != null ) {
			
			tcp.TargetPort.TargetPort = tcp;
			tcp.TargetPort.ClientType = PortClientType.CLIENT;
			tcp.TargetPort = null;
		}
	}
	
	void RefreshLinePortNameOnceClient()
	{
		foreach( n_MyObject.MyObject mo in myModuleList ) {
			if( !(mo is HardModule) ) {
				continue;
			}
			HardModule hm = (HardModule)mo;
			for( int n = 0; n < hm.PORTList.Length; ++n ) {
				Port cp = hm.PORTList[n];
				if( cp.CanChange ) {
					if( cp.TargetPort != null && cp.ClientType != PortClientType.CLIENT ) {
						cp.ClientType = PortClientType.CLIENT;
					}
				}
				if( cp.isDeal ) {
					continue;
				}
				if( cp.ClientType != PortClientType.CLIENT ) {
					continue;
				}
				//端口目标为Line端口
				if( cp.TargetPort != null && cp.TargetPort.CanChange ) {
					
					//如果名字为Line则跳过, 稍后会再处理一次
					if( cp.FuncName == PortFuncName.LINE ) {
						//MessageBox.Show( cp.Name + "///" );
						continue;
					}
					cp.isDeal = true;
					isOK = false;
					
					//如果为Master, 表明已经处理过 (端口非悬空), 跳过. 否则说明是悬空排脚
					if( cp.TargetPort.ClientType == PortClientType.MASTER ) {
						continue;
					}
					
					//把提取属性扩散到当前模块的其他同名端口上, 根据是否有链接对象设置为 MASTER 或 CLIENT
					HardModule thm = cp.TargetPort.Owner;
					for( int m = 0; m < thm.PORTList.Length; ++m ) {
						Port tcp = thm.PORTList[m];
						if( tcp.Name == cp.TargetPort.Name ) {
							if( tcp == cp.TargetPort ) {
								tcp.ClientType = PortClientType.MASTER;
							}
							else {
								tcp.ClientType = PortClientType.CLIENT;
							}
							tcp.FuncName = cp.FuncName;
						}
					}
				}
			}
		}
	}
	
	
	
	//定时运行
	public void Run()
	{
		
	}
	
	//重绘事件
	protected override void OnPaint(PaintEventArgs e)
	{
		//n_Debug.Debug.Message = CLineIndex.ToString();
		
		if( Pause ) return;
		
		Graphics g = e.Graphics;
		
		//if( NeedDraw != null ) {
		//	NeedDraw();
		//}
		
		g.SmoothingMode = SmoothingMode.HighQuality;
		
		if( SystemData.Mohu ) {
			//启用图像模糊效果
			g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
			g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
		}
		else {
			//禁用图像模糊效果
			g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
		}
		
		try {
		
		//MyModuleLibPanel.time++;
		
		//设置绘图目标
		SG.SetObject( g );
		
		//填充背景
		/*
		if( G.SimulateMode ) {
			g.FillRectangle( GUIset.BackBrushSim, -1, -1, this.Width+1, this.Height+1 );
		}
		else {
			g.FillRectangle( GUIset.BackBrush, -1, -1, this.Width+1, this.Height+1 );
		}
		*/
		g.FillRectangle( GUIset.BackBrush, -1, -1, this.Width+1, this.Height+1 );
		
		if( ShowExtendItem ) {
			//DrawEngine( g );
			//DrawCoor( g );
			//DrawResourceList( g );
		}
		
		//绘制导线颜色指示器
		if( myModuleList.SelectPort != null && !myModuleList.SelectPort.isBus ) {
			myLineColorBox.Draw( g );
		}
		
		//获取图形界面的边界
		MinX = 0;
		MaxX = 0;
		MinY = 0;
		MaxY = 0;
		
		float C_MinX = 0;
		float C_MaxX = 0;
		float C_MinY = 0;
		float C_MaxY = 0;
		Shape.GetArea( this, myModuleList, ref MinX, ref MinY, ref MaxX, ref MaxY, ref C_MinX, ref C_MinY, ref C_MaxX, ref C_MaxY );
		//g.DrawRectangle( AreaPen, this.StartX + MinX - 50, this.StartY + MinY - 50, MaxX - MinX + 100, MaxY - MinY + 100 );
		
		GUIcoder.ExistCircuit = Shape.ExistCircuit;
		GUIcoder.ExistLAPI = true; //Shape.ExistLAPI;
		isNoModule = Shape.NoVisibleModule;
		
		//绘制初始提示
		if( isNoModule ) {
			STip.Draw( g, StartX, StartY );
		}
		else {
			//开始界面放缩
			gl.ResetTransform();
			if( AScale != AScaleMid ) {
				g.ScaleTransform( (float)AScale/AScaleMid, (float)AScale/AScaleMid );
				gl.ScaleTransform( (float)AScale/AScaleMid, (float)AScale/AScaleMid );
			}
			g.TranslateTransform( StartX, StartY );
			gl.TranslateTransform( StartX, StartY );
			
			//if( GUIset.isDefault ) {
			
			//g.FillRectangle( GUIset.BackBrush, this.StartX + MinX - 100, this.StartY + MinY - 50, MaxX - MinX + 200, MaxY - MinY + 100 );
			g.DrawRectangle( AreaPen, MinX - 100, MinY - 100, MaxX - MinX + 200, MaxY - MinY + 200 );
			
			C_MinX -= 100;
			C_MaxX += 100;
			C_MinY -= 100;
			C_MaxY += 100;
			
			if( GUIcoder.ExistCircuit ) {
				//绘制网格
				for( int xx = (int)C_MinX; xx <= (int)C_MaxX/10*10; xx += 10 ) {
					
					/*
					if( xx /10*10 == 0 ) {
						g.DrawLine( Pens.SlateBlue, xx/10*10, MinY/10*10, xx/10*10, MaxY/10*10 );
					}
					else {
						g.DrawLine( Pens.Gainsboro, xx/10*10, MinY/10*10, xx/10*10, MaxY/10*10 );
					}
					 */
					g.DrawLine( Pens.Gainsboro, xx/10*10, (int)C_MinY/10*10, xx/10*10, (int)C_MaxY/10*10 );
				}
				for( int yy = (int)C_MinY; yy <= (int)C_MaxY/10*10; yy += 10 ) {
					
					/*
					if( yy /10*10 == 0 ) {
						g.DrawLine( Pens.SlateBlue, MinX/10*10, yy/10*10, MaxX/10*10, yy/10*10 );
					}
					else {
						g.DrawLine( Pens.Gainsboro, MinX/10*10, yy/10*10, MaxX/10*10, yy/10*10 );
					}
					 */
					g.DrawLine( Pens.Gainsboro, (int)C_MinX/10*10, yy/10*10, (int)C_MaxX/10*10, yy/10*10 );
				}
			}
				
			//}
			//else {
				//g.FillRectangle( GUIset.FreeAreaBrush, this.StartX + MinX - 100, this.StartY + MinY - 50, MaxX - MinX + 200, MaxY - MinY + 100 );
				
				//g.DrawRectangle( Pens.Black, this.StartX + MinX - 100, this.StartY + MinY - 50, MaxX - MinX + 200, MaxY - MinY + 100 );
				
				//g.FillRectangle( Brushes.SlateBlue, this.StartX + MinX - 100, this.StartY + MinY - 50, MaxX - MinX + 200, MaxY - MinY + 100 );
			//}
			//if( GUIset.isDefault ) {
			//	MyModuleLibPanel.SX = MaxX + 120;
			//	MyModuleLibPanel.SY = MinY - 50;
			//}
			EnginePair.SX = (int)MinX - 100;
			EnginePair.SY = (int)MinY - 400;
			
			CenterX = (int)((MaxX + MinX) / 2);
			CenterY = (int)((MaxY + MinY) / 2);
		}
		
		//绘制引擎匹配器
		EnginePair.Draw( g );
		
		//绘制分组
		mGroupList.Draw( g );
		
		//绘制组件列表
		myModuleList.DrawImage( g );
		
		//绘制电路线节点 (注意必须要放到模块后边绘制, 防止模块遮挡导线产生歧义)
		//但是这样就可能挡住模块的参数设置面板...
		myCLineList.Draw( g );
		
		//需要放到 myModuleList 之后，因为myModuleList里边清空了图片
		if( myModuleList.NeedDrawLineMap ) {
			myCLineList.DrawIndex( gl );
		}
		if( myModuleList.NeedDrawLineMap ) {
			myModuleList.NeedDrawLineMap = false;
		}
		
		//绘制导线节点
		myMidPortList.Draw( g );
		
		//... myCLineList.Draw( g );
		
		//绘制事件连接导线
		EL.Draw( g );
		
		//绘制高亮选中面板
		myModuleList.DrawHighLight( g );
		
		//绘制指令说明
		for( int i = 0; i < ObjectMesPanelList.Length; ++i ) {
			ObjectMesPanelList[i].Draw( g );
		}
		
		//绘制选中面板
		SelPanel.Draw( g );
		
		//运行时显示py变量
		if( G.SimulateMode && G.ccode.b_ExistPython ) {
			
			GraphicsState gspy = g.Save();
			g.TranslateTransform( MaxX, MinY );
			//g.FillRectangle( PyVarBackBrush, 0, 0, Width, Height );
			n_PyVar.PyVar.Draw( g );
			g.Restore( gspy );
		}
		//运行时显示全部变量
		if( G.ShowAllVar ) {
			
			GraphicsState gspy = g.Save();
			g.TranslateTransform( MaxX, MinY );
			DrawVar( g );
			g.Restore( gspy );
		}
		if( isNoModule ) {
			//...
		}
		else {
			//结束界面放缩
			g.TranslateTransform( -StartX, -StartY );
			if( AScale != AScaleMid ) {
				g.ScaleTransform( AScaleMid / (float)AScale, AScaleMid / (float)AScale );
			}
			/*
			if( tempAScale != AScale ) {
				
				float mapx = MouseX * AScaleMid / tempAScale - StartX - modX;
				float mapy = MouseY * AScaleMid / tempAScale - StartY - modY;
				if( tempAScale < AScale ) {
					
					tempAScale = tempAScale * 108/100;
					if( tempAScale > AScale ) {
						tempAScale = AScale;
					}
					tempAScale = AScale;
				}
				if( tempAScale > AScale ) {
					
					tempAScale = tempAScale * 92 / 100;
					if( tempAScale < AScale ) {
						tempAScale = AScale;
					}
					tempAScale = AScale;
				}
				float fStartX = MouseX * AScaleMid / tempAScale - mapx;
				float fStartY = MouseY * AScaleMid / tempAScale - mapy;
				StartX = (int)fStartX;
				StartY = (int)fStartY;
				modX = fStartX - StartX;
				modY = fStartY - StartY;
				
				Invalidate();
			}
			*/
		}
		
		//g.DrawImage( LineMap, 500, 500 );
		
		//绘制标题栏
		GHead.Draw( g );
		
		//历史记录
		DrawHistory( g );
		
		//绘制垃圾桶
		myRecycler.Draw( g );
		
		//绘制资源使用图表
		if( n_ModuleLibPanel.MyModuleLibPanel.LabType != n_GUIcoder.labType.Game ) {
			DrawSysResUse( g );
		}
		
		//绘制放缩标尺
		DrawScale( g );
		
		if( G.commonEXPBox.ePanel.Visible ) {
			g.FillRectangle( ShowInsBackBrush, -1, -1, this.Width+1, this.Height+1 );
		}
		
		if( ShowExtendItem ) {
			//DrawSmallMap( g );
		}
		
		//绘制边框
		//g.DrawRectangle( Pens.White, 0, 0, this.Width - 1, this.Height - 1 );
		//g.DrawRectangle( Pens.Blue, 1, 1, this.Width - 3, this.Height - 3 );
		
		//临时, 绘制按键值
		//g.DrawString( KeyDownString, mFont, Brushes.White, 40, 40 );
		
		if( G.SimulateMode ) {
			a0++;
			a1 -= 2;
			a2 += 3;
			//g.DrawEllipse( Pens.Yellow, 215, Height - 80, 75, 75 );
			//if( SystemData.isBlack ) {
			//	g.DrawString( "仿真模式", WarningFont, Brushes.Yellow, 210, Height - 22 );
			//}
			//else {
			//	g.DrawString( "仿真模式", WarningFont, Brushes.OrangeRed, 210, Height - 22 );
			//}
			//DrawEngine( g );
		}
		
		/*
		if( CKeys != Keys.None ) {
			g.DrawString( CKeys.ToString() + ": " + (int)CKeys, WarningFont, Brushes.Black, 200, 100 );
		}
		*/
		
		//显示调试信息
		if( n_Debug.Debug.Message != null ) {
			string[] cut = n_Debug.Debug.Message.Split( '\n' );
			for( int i = 0; i < cut.Length; ++i ) {
				g.DrawString( cut[i], WarningFont, Brushes.Red, 220, 100 + i * 15 );
			}
		}
		/*
		//显示提示信息
		if( n_Debug.Warning.ClashMessage != null || n_Debug.Warning.LoadMessage != null ) {
			g.FillRectangle( Brushes.Goldenrod, 0, Height - 100, Width, 100 );
			if(  n_Debug.Warning.ClashMessage != null ) {
				g.DrawString( n_Debug.Warning.ClashMessage, WarningFont, Brushes.Black, 50, Height - 95 );
			}
			if(  n_Debug.Warning.LoadMessage != null ) {
				g.DrawString( n_Debug.Warning.LoadMessage, WarningFont, Brushes.Black, 50, Height - 95 );
			}
		}
		*/
		if( n_Debug.Warning.ErrMessage != null ) {
			DrawRectangleText( g, 3, n_Debug.Warning.ErrMessage, ref MesY3 );
		}
		else {
			MesY3 = 0;
		}
		if( n_Debug.Warning.ClashMessage != null ) {
			DrawRectangleText( g, 2, n_Debug.Warning.ClashMessage, ref MesY2 );
		}
		else {
			MesY2 = 0;
		}
		if( n_Debug.Warning.WarningMessage != null ) {
			DrawRectangleText( g, 1, n_Debug.Warning.WarningMessage, ref MesY1 );
		}
		else {
			MesY1 = 0;
		}
		if( G.PushBox.TickNumber != 0 ) {
			g.DrawString( "准备中...(" + G.PushBox.TickNumber + ")", WarningFont, Brushes.RoyalBlue, Width / 2 - 20, 70 );
		}
		
		if( G.StartStatus ) {
			//int sx = n_Head.Head.HeadWidth + n_Head.Head.ShowX + 10;
			//g.DrawString( "<- 鼠标拖动左侧的橙色竖条, 可调节左边栏的默认位置", WarningFont, Brushes.SlateGray, sx, Height - 30 );
		}
		ErrorTimes = 0;
		
		/*
		//显示帮助信息
		if( CKeys == Keys.ShiftKey ) {
			string s = "1. 按住ctrl键为自锁模式, 鼠标点击可独立触发多个传感器\n";
			s = "2. 按住左Shift键+字母键的同时, 鼠标点击传感器, 系统会绑定对应字母按键和传感器, 可用按键代替鼠标触发传感器\n";
			s = "3. 按住左上角ESC键的同时, 鼠标点击传感器, 可解除传感器按键绑定,解除后则只能通过鼠标点击触发";
			g.DrawString( s, WarningFont, Brushes.SlateGray, Width - 150, Height - 80 );
		}
		*/
		
		if( ShowMessage ) {
			if( n_ModuleLibPanel.MyModuleLibPanel.FloatButton ) {
				g.FillRectangle( ShowStartBackBrush, -1, -1, this.Width+1, this.Height+1 );
				//if( isNoModule && myModuleList.isShowWarning ) {
				SWTip.Draw( g, StartX, StartY );
				//}
			}
			else {
				g.FillRectangle( ShowMesBackBrush, -1, -1, this.Width+1, this.Height+1 );
				if( n_AVRdude.AVRdude.ErrorMes == null ) {
					g.FillRectangle( Brushes.CornflowerBlue, -1, Height / 3, this.Width+1, this.Height / 3 );
					g.DrawImage( downloadok, 20, Height/2 - downloadok.Height/2 );
					SG.MString.DrawAtCenter( "下载完成", Color.WhiteSmoke, 50, Width / 2, Height / 2 );
				}
				else {
					bool maybe = n_AVRdude.AVRdude.ErrorMes.StartsWith( "*" );
					if( maybe ) {
						g.FillRectangle( Brushes.DarkKhaki, -1, Height / 3, this.Width+1, this.Height / 3 );
						g.DrawImage( downloadwarning, 20, Height/2 - downloadwarning.Height/2 );
						SG.MString.DrawAtCenter( "下载结束", Color.WhiteSmoke, 50, Width / 2, Height / 2 );
					}
					else {
						g.FillRectangle( Brushes.SandyBrown, -1, Height / 3, this.Width+1, this.Height / 3 );
						g.DrawImage( downloaderror, 20, Height/2 - downloaderror.Height/2 );
						SG.MString.DrawAtCenter( "下载失败", Color.WhiteSmoke, 50, Width / 2, Height / 2 );
					}
					SG.MString.DrawAtCenter( n_AVRdude.AVRdude.ErrorMes, Color.WhiteSmoke, 25, Width / 2, Height / 3 * 2 + 50 );
					SG.MString.DrawAtCenter( n_AVRdude.AVRdude.ErrorMes1, Color.WhiteSmoke, 25, Width / 2, Height / 3 * 2 + 135 );
				}
			}
		}
		
		//判断是否有出错模块并移动到目标位置处
		if( GUIcoder.AutoMove && GUIcoder.ErrorObject != null ) {
			int midx = -StartX + Width / 2 * AScaleMid / AScale;
			int midy = -StartY + Height / 2 * AScaleMid / AScale;
			
			int absx = Math.Abs( midx - GUIcoder.ErrorObject.MidX );
			int absy = Math.Abs( midy - GUIcoder.ErrorObject.MidY );
			
			//AScale = AScaleMax * tempLength / (tempLength + (absx + absy));
			
			int off = 7 * AScaleMid / AScale;
			if( off < 7 ) {
				off = 7;
			}
			
			if( absx > off || absy > off ) {
				if( midx < GUIcoder.ErrorObject.MidX - off ) {
					StartX -= off;
				}
				if( midx > GUIcoder.ErrorObject.MidX + off ) {
					StartX += off;
				}
				if( midy < GUIcoder.ErrorObject.MidY - off ) {
					StartY -= off;
				}
				if( midy > GUIcoder.ErrorObject.MidY + off ) {
					StartY += off;
				}
				MyRefresh();
			}
			else {
				GUIcoder.AutoMove = false;
				GUIcoder.ErrorObject = null;
			}
		}
		
		
		//g.ResetTransform();
		//g.DrawImage( LineMap, 0, 0 );
		
		
		}
		catch (Exception er) {
			ErrorTimes++;
			if( ErrorTimes == 3 ) {
				
				try {
					//this.Close();
				}
				catch {}
				G.SystemError( G.ccode.PathAndName, er.ToString() );
			}
		}
		
		isLoading = false;
		
		//Rectangle r = new Rectangle( 0, 0, Width / 2, Height );
		//g.SetClip( r );
		
		//G.SimBox.SPanel.MyDraw( g );
	}
	
	//type: 0- 消息推送(新版本)
	//type: 1- 命名规则, 多个控制器, ....
	//type: 2- 未找到的模块, 连线错误, ...
	void DrawRectangleText( Graphics g, int type, string text, ref float MesY )
	{
		int StartX = (n_Head.Head.HeadWidth + n_Head.Head.ShowX);
		int AreaWidth = Width - StartX;
		int max_width = AreaWidth - 200;
		
		int img_h = 40;
		int left_pad = 10;
		int img_pad = img_h + left_pad*2;
		
		SizeF sz = g.MeasureString( text, WarningFont, max_width );
		
		float y = Height - sz.Height - 30;
		if( y < Height * 2 / 3 ) {
			y = Height * 2 / 3;
		}
		if( y > Height - 100 ) {
			//y = Height  - 100;
		}
		if( MesY == 0 ) {
			MesY = Height;
		}
		if( MesY > y ) {
			float offset = (MesY - y) / 10;
			if( offset < 1 ) {
				offset = 1;
			}
			MesY -= offset;
			MyRefresh();
		}
		
		RectangleF sr = new RectangleF( StartX + img_pad/2 + (AreaWidth - sz.Width)/2, MesY, sz.Width, sz.Height );
		
		//g.FillRectangle( Brushes.YellowGreen, sr );
		
		RectangleF sr1 = new RectangleF( sr.X - img_pad, MesY - 20, sr.Width + img_pad, sr.Height + 40 );
		GraphicsPath Rsgp = Shape.CreateRoundedRectanglePath1( sr1 );
		
		if( type == 1 ) {
			g.FillPath( MesBrush1, Rsgp );
			g.DrawPath( Pens.DarkGray, Rsgp );
			g.DrawImage( ImgMes1, sr1.X + left_pad, sr1.Y + ( sr1.Height - img_h )/2, img_h, img_h );
			//g.DrawString( "任意位置点击鼠标可清除本消息", WarningFont, Brushes.CornflowerBlue, sr1.X + 10, sr1.Y - 20 );
			g.DrawString( text, WarningFont, Brushes.DarkSlateGray, sr );
		}
		else if( type == 2 ) {
			g.FillPath( MesBrush2, Rsgp );
			g.DrawPath( Pens.Black, Rsgp );
			g.DrawImage( ImgMes2, sr1.X + left_pad, sr1.Y + ( sr1.Height - img_h )/2, img_h, img_h );
			//g.DrawString( "请参考以下报警信息解决问题, 如需技术支持可到linbkoy官网联系我们: www.linkboy.cc", WarningFont, Brushes.GreenYellow, sr1.X + 10, sr1.Y - 20 );
			g.DrawString( text, WarningFont, Brushes.DarkSlateGray, sr );
		}
		else {
			g.FillPath( MesBrush3, Rsgp );
			g.DrawPath( Pens.Black, Rsgp );
			g.DrawImage( ImgMes3, sr1.X + left_pad, sr1.Y + ( sr1.Height - img_h )/2, img_h, img_h );
			//g.DrawString( "请参考以下报警信息解决问题, 如需技术支持可到linbkoy官网联系我们: www.linkboy.cc", WarningFont, Brushes.GreenYellow, sr1.X + 10, sr1.Y - 20 );
			g.DrawString( text, WarningFont, Brushes.Black, sr );
		}
	}
	
	//绘制系统资源占用情况
	bool MouseOnRes = false;
	public int R1 = 30000;
	public int R2 = 2303;
	public bool ShowFlashLimitWarning = false;
	public int ShowRamLimitWarning = 0;
	public int r1;
	public int r2;
	
	void DrawSysResUse( Graphics g )
	{
		int SoftSP_StartAddress = 0;
		
		//获取软件堆栈起始地址
		if( n_CodeData.CodeData.TotalByteNumber != 0 ) {
			int VdataIndex = n_VdataList.VdataList.GetIndex( n_VarType.VarType.VBase );
			SoftSP_StartAddress = n_AddressList.AddressList.StaticMaxAddr[ VdataIndex ] + n_Interrupt.Interrupt.GetStackNumber() + StartNeedNumber + 3;
		}
		
		//int StartAddress = n_VdataList.VdataList.Get( VdataIndex ).StartAddressConst;
		//int EndAddress = n_VdataList.VdataList.Get( VdataIndex ).EndAddress;
		
		//labelROM.Text = "已用FLASH空间: " + n_CodeData.CodeData.TotalByteNumber + "字节 / 共计32768字节\n" +
		//				"已用RAM空间: " + SoftSP_StartAddress + "字节 / 共计2048字节";
		//				//"中断空间: " + EndAddress + "\n" +
		
		int Length = 150;
		int sx = Width - Length - 95;//867;//700 + Head.ButtonNumber * Head.XO;
		if( sx < Head.FreeStartX ) {
			sx = Head.FreeStartX;
		}
		
		sx = Head.FreeStartX;
		if( G.Loongson ) {
			sx -= 40;
		}
		
		int sy = 18;
		
		//SG.MRectangle.FillRound( Color.DarkSeaGreen, 13, 13, sx - 40, sy - 7, Length + 8 + 60, 26 );
		
		r1 = n_CodeData.CodeData.TotalByteNumber;
		r2 = SoftSP_StartAddress + 1;
		
		if( n_Config.Config.CPUExist() && n_Config.Config.GetCPU() == n_CPUType.CPUType.MEGA328 ) {
			R1 = 30000;
			R2 = 2048 + 256;
		}
		if( n_Config.Config.CPUExist() && n_Config.Config.GetCPU() == n_CPUType.CPUType.MEGA644 ) {
			R1 = 60000;
			R2 = 4096 + 256;
		}
		if( n_Config.Config.CPUExist() && n_Config.Config.GetCPU() == n_CPUType.CPUType.MEGA2560 ) {
			R1 = 256000;
			R2 = 8192 + 256;
		}
		if( n_Config.Config.CPUExist() && n_Config.Config.GetCPU() == n_CPUType.CPUType.VM ) {
			n_VexLoaderForm.VexLoaderForm.UseROM = r1;
			n_VexLoaderForm.VexLoaderForm.UseRAM = r2;
			R1 = n_VexLoaderForm.VexLoaderForm.ROM_Size;
			R2 = n_VexLoaderForm.VexLoaderForm.RAM_Size;
		}
		
		if( G.SimulateMode ) {
			n_CodeData.CodeData.TotalByteNumber = 0;
			r1 = 0;
			r2 = 0;
		}
		//提示信息并设置状态量
		string mes = "";
		if( r1 >= R1 && R1 > 0 ) {
			ShowFlashLimitWarning = true;
			mes += "程序ROM已超出限制, ";
		}
		else {
			ShowFlashLimitWarning = false;
		}
		//提示信息并设置状态量
		if( r2 > R2 && R2 > 0 ) { //原来是 >= 有隐患 改为了 >, 前边r2加上1作为保护
			ShowRamLimitWarning = r2 - R2;
			
			if( Flash ) {
				g.FillRectangle( Brushes.Gold, 0, Head.HeadLabelHeight - 1, Width, 42 );
			}
			mes += "系统RAM已满, 需减小字符串/数组的长度/";
		}
		else {
			ShowRamLimitWarning = 0;
		}
		//判断是否提示信息
		if( ShowRamLimitWarning != 0 || ShowFlashLimitWarning ) {
			mes += "删除一些无用模块或者更换为更大容量的主板\nROM:" + r1 + "(" + R1 + "), RAM:" + r2 + "(" + R2 + ")";
			if( Flash ) {
				g.FillRectangle( Brushes.Gold, 0, Head.HeadLabelHeight - 1, Width, 42 );
			}
			SG.MString.DrawAtCenter( mes, Color.Black, 11, Width/2, sy + 55 );
		}
		int ox = 30;
		
		Color textColor = Color.Black;
		if( GUIset.BlackHead ) {
			textColor = Color.LightSlateGray;
		}
		
		if( r1 >= R1 ) {
			//r1 = R1;
		}
		SG.MLine.Draw( Color.LightSlateGray, 4, sx + ox, sy + 2, sx + ox + Length, sy + 2 );
		if( R1 > 0 ) {
			SG.MLine.Draw( Color.WhiteSmoke, 2, sx + ox + Length * r1 / R1, sy + 2, sx + ox, sy + 2 );
		}
		SG.MString.DrawAtLeft( "ROM: " + r1 + " / " + R1, textColor, 9, sx + ox, sy + 2 - 12 );
		
		if( r2 >= R2 ) {
			//r2 = R2;
		}
		SG.MLine.Draw( Color.LightSlateGray, 4, sx + ox, sy + 14, sx + ox + Length, sy + 14 );
		if( R2 > 0 ) {
			SG.MLine.Draw( Color.Orange, 2, sx + ox + Length * r2 / R2, sy + 14, sx + ox, sy + 14 );
		}
		SG.MString.DrawAtLeft( "RAM: " + r2 + " / " + R2, textColor, 9, sx + ox, sy + 13 + 12 );
		
		if( MouseOnRes ) {
			//...
		}
	}
	
	//绘制放缩标尺
	void DrawScale0( Graphics g )
	{
		int Length = 150;
		//int sx = 387;
		int sx = Width - 6; // - 60 - 5
		//int sy = Height - 85 - Length;
		int sy = 32;
		
		SG.MLine.Draw( Color.Silver, 3, sx, sy, sx, sy + Length - Length/20 );
		
		SG.MCircle.Fill( Color.OrangeRed, sx, sy + 10 * Length / ScaleList.Length, 3 );
		
		SG.MCircle.Fill( Color.Blue, sx, sy + (20 - ScaleIndex) * Length / ScaleList.Length, 4 );
	}
	
	//绘制放缩标尺
	void DrawScale( Graphics g )
	{
		int Length = 100;
		//int sx = 387;
		int sx = Width - 6; // - 60 - 5
		//int sy = Height - 85 - Length;
		int sy = Height - 0 - Length;
		
		SG.MLine.Draw( Color.LightSteelBlue, 7, sx, sy, sx, sy + Length - Length/20 );
		
		SG.MCircle.Fill( Color.LightSlateGray, sx, sy + 10 * Length / ScaleList.Length, 5 );
		
		SG.MCircle.Fill( Color.OrangeRed, sx, sy + (20 - ScaleIndex) * Length / ScaleList.Length, 3 );
	}
	
	//绘制撤销重做线序图
	void DrawHistory( Graphics g )
	{
		int ii = n_Head.Head.COnIndex - n_Head.Head.ExtStartIndex;
		if( ii == 0 || ii == 1 ) {
			
			float t = UndoNumber + RedoNumber;
			float x = n_Head.Head.HeadWidth + 30;
			float y = n_Head.Head.HeadLabelHeight + 20;
			float ex = Width - 265;
			
			g.DrawLine( HistoryPen, x, y, ex, y );
			for( int i = 0; i <= t; ++i ) {
				g.FillEllipse( Brushes.WhiteSmoke, x + (ex-x) * i / t - 5, y - 5, 10, 10 );
			}
			g.FillEllipse( Brushes.SkyBlue, x + (ex-x) * UndoNumber / t - 7, y - 7, 14, 14 );
			g.DrawEllipse( Pens.SteelBlue, x + (ex-x) * UndoNumber / t - 7, y - 7, 14, 14 );
		}
	}
	
	//绘制坐标系
	void DrawCoor( Graphics g )
	{
		int PerR = 50;
		
		//绘制坐标系
		for( int i = 0; i < 40; ++i ) {
			int y = PerR * i + StartY % PerR;
			if( y > this.Height ) {
				break;
			}
			g.DrawLine( Pens.DarkGreen, 0, y, this.Width, y );
		}
		for( int i = 0; i < 40; ++i ) {
			int x = PerR * i + StartX % PerR;
			if( x > this.Width ) {
				break;
			}
			g.DrawLine( Pens.DarkGreen, x, 0, x, this.Height );
		}
		//绘制原点十字光标
		g.DrawLine( Pens.SlateGray, - 30, 0, StartX + 30, StartY );
		g.DrawLine( Pens.SlateGray, 0, - 30, StartX, StartY + 30 );
		g.DrawEllipse( Pens.SlateGray, - 20, - 20, 40, 40 );
	}
	
	//绘制小地图
	void DrawSmallMap( Graphics g )
	{
//		if( this.Width == 0 ) {
//			return;
//		}
//		int Mult = BufferImageWidth / ( this.Width / 8 );
//		
//		int MidWidth1 = BufferImageWidth / Mult;
//		int MidHeight1 = BufferImageHeight / Mult;
//		int MidWidth2 = this.Width / Mult;
//		int MidHeight2 = this.Height / Mult;
//		
//		int CenterX = MidWidth2 * 2 / 3;
//		int CenterY = MidHeight2 * 2 / 3;
//		
//		int MidX1 = ( StartX + ( -this.Width + BufferImageWidth ) / 2 ) / Mult;
//		int MidY1 = ( StartY + ( -this.Height + BufferImageHeight ) / 2 ) / Mult;
//		int CrossX = MidX1 - MidWidth1 / 2 + CenterX;
//		int CrossY = MidY1 - MidHeight1 / 2 + CenterY;
//		
//		int MidX2 = CenterX;
//		int MidY2 = CenterY;
//		g.FillRectangle( RFBrush, MidX2 - MidWidth2 / 2, MidY2 - MidHeight2 / 2, MidWidth2, MidHeight2 );
//		
//		//绘制组件列表
//		for( int i = 0; i < myModuleList.ModuleList.Length; ++i ) {
//			if( myModuleList.ModuleList[ i ] == null ) {
//				continue;
//			}
//			if( !(myModuleList.ModuleList[ i ] is HardModule) ) {
//				continue;
//			}
//			HardModule m = (HardModule)myModuleList.ModuleList[ i ];
//			
//			g.DrawImage( m.BImage,
//			            CrossX + ( m.MidX - m.BImage.Width / 2 ) / Mult,
//			            CrossY + ( m.MidY - m.BImage.Height / 2 ) / Mult,
//			            m.BImage.Width / Mult, m.BImage.Height / Mult );
//			//g.DrawRectangle( Pens.White,
//			//            CrossX + ( m.X - m.BImage.Width / 2 ) / Mult,
//			//           CrossY + ( m.Y - m.BImage.Height / 2 ) / Mult,
//			//            m.BImage.Width / Mult, m.BImage.Height / Mult );
//		}
//		g.DrawRectangle( RDPen, MidX2 - MidWidth2 / 2, MidY2 - MidHeight2 / 2, MidWidth2, MidHeight2 );
//		
//		//绘制小原点十字光标
//		g.DrawLine( Pens.Yellow, CrossX - 10, CrossY, CrossX + 10, CrossY );
//		g.DrawLine( Pens.Yellow, CrossX, CrossY - 10, CrossX, CrossY + 10 );
	}
	
	//绘制引擎
	void DrawEngine( Graphics g )
	{
		//绘制引擎图标
		int Ex = 235;
		int Ey = this.Height - 45;
		
		//g.DrawString( myModuleList.RunNumber.ToString(), NumberFont, Brushes.White, Ex + 95, Ey + 7 );
		
		//中心点
		g.FillEllipse( Brushes.WhiteSmoke, Ex - 5, Ey - 5, 10, 10 );
		
		//边界环
		g.DrawArc( p0, Ex - 20, Ey - 20, 40, 40, a0, 100 );
		g.DrawArc( p0, Ex - 20, Ey - 20, 40, 40, a0 + 120, 100 );
		g.DrawArc( p0, Ex - 20, Ey - 20, 40, 40, a0 + 240, 100 );
		
		//外圈
		g.DrawEllipse( pb1, Ex - 15, Ey - 15, 30, 30 );
		g.DrawArc( p1, Ex - 15, Ey - 15, 30, 30, a1, 140 );
		//g.DrawArc( pl1, Ex - 15, Ey - 15, 30, 30, a1, 140 );
		
		//内圈
		g.DrawEllipse( pb2, Ex - 10, Ey - 10, 20, 20 );
		g.DrawArc( p2, Ex - 10, Ey - 10, 20, 20, a2, 80 );
		//g.DrawArc( pl2, Ex - 10, Ey - 10, 20, 20, a2, 80 );
	}
	
	//绘制所有变量
	void DrawVar( Graphics g )
	{
		//虚拟机内存
		byte[] BASE = n_UserModule.UserModule.BASE;
		
		int Idx = 0;
		for( int i = 0; i < n_VarList.VarList.length; ++i ) {
			n_VarNode.VarNode vn = n_VarList.VarList.Get( i );
			
			string str = null;
			long d = 0;
			if( vn.isConst ) {
				
			}
			else if( vn.ActiveType == n_MemberType.MemberType.StoreType.Static ) {
				
				int Address = 0;
				try {
					Address = int.Parse( vn.Address );
				}
				catch {
					continue;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Bool ) {
					d = n_Data.Data.GetInt8( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Bit ) {
					//d = n_Data.Data.GetInt8( BASE, Address );
					//str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Sint8 ) {
					d = n_Data.Data.GetInt8( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Sint16 ) {
					d = n_Data.Data.GetInt16( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Sint32 ) {
					d = n_Data.Data.GetInt32( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.fix ) {
					d = n_Data.Data.GetInt32( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Uint8 ) {
					d = n_Data.Data.GetUint8( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Uint16 ) {
					d = n_Data.Data.GetUint16( BASE, Address );
					str = vn.Name;
				}
				if( vn.Type == n_VarType.VarType.BaseType.Uint32 ) {
					d = n_Data.Data.GetUint32( BASE, Address );
					str = vn.Name;
				}
			}
			else {
				//...
			}
			if( str != null ) {
				g.DrawString( d.ToString(), GUIset.Font12, Brushes.MediumVioletRed, 2550, Idx * 25 );
				g.DrawString( (vn.Type + ":" + str), GUIset.Font12, Brushes.Gray, 2580, Idx * 25 );
				Idx++;
			}
		}
	}
	
	//绘制资源占用列表
	void DrawResourceList( Graphics g )
	{
		for( int i = 0; i < myModuleList.myResourceList.Number; ++i ) {
			string ResName = myModuleList.myResourceList.GetName( i );
			string UserName = myModuleList.myResourceList.GetUser( i );
			g.DrawString( ResName + ":\t" + UserName, NumberFont, Brushes.White, 20, 100 + i * 20 );
		}
	}
	
	//添加新的模块
	void AddNewModule( MyObject CModule, int MouseOnBaseX, int MouseOnBaseY )
	{
		ImagePanel TargetGPanel = G.CGPanel;
		
		NewObject = CModule;
		LastCenterX = CenterX;
		LastCenterY = CenterY;
		
		//判断添加的是否为变量
		if( CModule is GVar ) {
			GVar gv0 = (GVar)CModule;
			GVar gv = new GVar();
			int Vari = 1;
			string VarNewName = gv0.Name;
			while( true ) {
				if( !TargetGPanel.myModuleList.NameisUsed( VarNewName ) ) {
					break;
				}
				VarNewName = gv0.Name + Vari;
				++Vari;
			}
			gv.isNewTick = MyObject.MaxNewTick;
			gv.ignoreHit = true;
			gv.SetUserValue(
				VarNewName,
				null,
				gv0.VarType,
				"",
				gv0.Value,
				gv0.isConst,
				MouseOnBaseX - gv0.SX,
				MouseOnBaseY - gv0.SY
				);
			TargetGPanel.myModuleList.Add( gv );
			return;
		}
		//判断添加的是否为注释
		if( CModule is GNote ) {
			GNote gv0 = (GNote)CModule;
			
			string Mes = gv0.Value;
			string Path = gv0.Name;
			
			string text = n_OS.VIO.OpenTextFile(  OS.ModuleLibPath + Mes );
			
			G.CGPanel.Pause = true;
			n_MyObject.MyObject mo = n_GUIcoder.GUIcoder.AddTextToGPanel( G.CGPanel, text );
			if( mo != null ) {
				n_GUIcoder.GUIcoder.ErrorObject = mo;
				G.CGPanel.AddMesPanel( "刚刚粘贴的元素在这里", 1, mo );
				n_GUIcoder.GUIcoder.AutoMove = true;
			}
			G.CGPanel.Pause = false;
			
			/*
			GNote gm = new GNote();
			gm.SetUserValue( "描述", null, gv0.Value, MouseOnBaseX - gv0.SX, MouseOnBaseY - gv0.SY, 150 );
			gm.ignoreHit = true;
			gm.isNewTick = MyObject.MaxNewTick;
			TargetGPanel.myModuleList.Add( gm );
			*/
			
			return;
		}
		MyFileObject CurrentModule = (MyFileObject)CModule;
		
		
		//判断是否为内测主板
		if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "dfl\\microbit\\main\\Pack.B" ) {
			MessageBox.Show( "此类型主板 micro:bit 为内测状态，您不是内测用户，暂无使用权限。" );
			return;
		}
		/*
		//判断是否为内测主板
		if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "dfl\\zkb\\Pack.B" ) {
			MessageBox.Show( "此类型主板 掌控板 为内测状态，您不是内测用户，暂无使用权限。根据测试规划，预计2019年9月内测完成并向普通用户开放。（可能会稍晚于micro:bit开放）" );
			return;
		}
		*/
		
		
		//判断是否积木类组件
		string ExtFile = null;
		if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\8X8\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\8X8LED点阵扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\1602\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\1602液晶屏扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\seg4\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\4位数码管扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\motor\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\2路马达扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\motor4\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\4路马达扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\nrf2401\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\无线通信扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\rc522\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\射频卡扩展\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\study\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\入门学习板\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\ESP8266\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\物联网wifi-ESP8266\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\LD3320\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\语音识别板LD3320\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\644board\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\644扩展板\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\wifiMotor\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\wifi马达扩展板\\0.lab";
		}
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\otto\\Pack.B" ) {
			ExtFile = OS.SystemRoot + "arduino-ext\\otto\\0.lab";
		}
		
		//判断是否为掌控板组合模块
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "dfl\\zkb\\main\\Pack.B" ) {
			ExtFile = OS.SystemRoot + @"Lib\dfl\zkb\zkb.lab";
		}
		//判断是否为小熊派组合模块
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "GD32\\BearPi\\Pack.B" ) {
			ExtFile = OS.SystemRoot + @"arduino-ext\小熊派\0.lab";
		}
		//判断是否为智控板
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\智控板12864\\Pack.B" ) {
			ExtFile = OS.SystemRoot + @"arduino-ext\340BOARD\12864屏幕\0.lab";
		}
		//判断是否为智控板
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "temp\\ext\\智控板IPS240X240\\Pack.B" ) {
			ExtFile = OS.SystemRoot + @"arduino-ext\340BOARD\IPS240X240\0.lab";
		}
		//判断是否为创客景林keli12
		else if( CurrentModule.MacroFilePath == OS.ModuleLibPath + "第三方模块库\\创客景林keji12\\main\\Pack.B" ) {
			ExtFile = OS.SystemRoot + @"arduino-ext\创客景林\0.lab";
		}
		else {
			//...
			//MessageBox.Show( CurrentModule.MacroFilePath );
		}
		if( ExtFile != null && ExtOpenFile != null ) {
			ExtOpenFile( ExtFile );
			return;
		}
		
		//判断是否为添加专属主板
		if( CurrentModule.ImageName == "sys_addmyboard" ) {
			
			MessageBox.Show( "即将打开主板编辑器, 请编辑完成后点击保存, 并导出到其他位置, 防止删除linkboy软件导致您的主板文件丢失. 然后点击右上角系统设置, 打开模块库管理器勾选<用户自定义主板>, 重启软件即可看到自定义主板模块了." );
			
			Process Proc = new Process();
			Proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
			if( CurrentModule.Name == "编辑我的nano主板" ) {
				Proc.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory + @"lib\user\nanox\Module.M";
			}
			else {
				Proc.StartInfo.Arguments = AppDomain.CurrentDomain.BaseDirectory + @"lib\user\uno\Module.M";
			}
			Proc.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
			Proc.StartInfo.FileName = @"LM-design.exe";//调用汇编命令
			Proc.Start();
			return;
		}
		//判断是否为打开IDE
		if( CurrentModule.MacroFilePath == OS.ModuleLibPath + @"circuit\0IDE\ASM\Module.M" ) {
			if( G.LIDEBox == null ) {
				G.LIDEBox = new n_LIDEForm.LIDEForm();
			}
			G.LIDEBox.Run();
			return;
		}
		//设置默认语言
		int LanguageIndex = 0;
		for( int li = 0; li < CurrentModule.LanguageList.Length; ++li ) {
			if( CurrentModule.LanguageList[ li ] == SystemData.ModuleLanguage ) {
				LanguageIndex = li;
				break;
			}
		}
		//搜索一个未用的名字
		string NewName = CurrentModule.NameList[ 2 + LanguageIndex ];
		int i = 1;
		while( true ) {
			if( !TargetGPanel.myModuleList.NameisUsed( NewName ) ) {
				break;
			}
			NewName = CurrentModule.NameList[ 2 + LanguageIndex ] + i;
			++i;
		}
		//设置组件属性
		//HardModule m = (HardModule)CurrentModule;
		HardModule m = GUIcoder.GetModuleFromMacroFile( CurrentModule.MacroFilePath );
		m.isNewTick = MyObject.MaxNewTick;
		m.ignoreHit = true;
		m.SetUserValue( NewName, null, CurrentModule.LanguageList[ LanguageIndex ],
		               MouseOnBaseX - CurrentModule.SX,
		               MouseOnBaseY - CurrentModule.SY,
		               0, false );
		
		//添加到当前图形界面上
		myModuleList.ShowMessage = true;
		if( m.isClientModule ) {
			UIModule c = new UIModule( m );
			
			if( c.isClientControlPad ) {
				c.BackColor = Color.FromArgb( 230, 230, 255 );
			}
			else if( TargetGPanel.myModuleList.LastUIModule != null &&
			        ( c.GetControlType() == ControlType.Button ||
			          c.GetControlType() == ControlType.Label ||
			          c.GetControlType() == ControlType.NumberBox ||
			          c.GetControlType() == ControlType.TrackBar ||
			          c.GetControlType() == ControlType.CheckBox ||
			          c.GetControlType() == ControlType.Sprite
			         ) ) {
				c.Width = TargetGPanel.myModuleList.LastUIModule.Width;
				c.Height  = TargetGPanel.myModuleList.LastUIModule.Height;
				c.BackColor = TargetGPanel.myModuleList.LastUIModule.BackColor;
				c.ForeColor = TargetGPanel.myModuleList.LastUIModule.ForeColor;
				c.TextFont = TargetGPanel.myModuleList.LastUIModule.TextFont;
				c.FrameColor = TargetGPanel.myModuleList.LastUIModule.FrameColor;
			}
			if( c.isClientControlPad ) {
				TargetGPanel.myModuleList.AddFirst( c );
			}
			else {
				TargetGPanel.myModuleList.Add( c );
			}
		}
		else {
			if( m.ImageName == SPMoudleName.mbb ) {
				TargetGPanel.myModuleList.Addmbb( m );
			}
			else {
				TargetGPanel.myModuleList.Add( m );
			}
			
			//判断是否需要添加电源按钮
//			if( m.isControlModule && m.ImageName.IndexOf( '-' ) == -1 && m.ImageName != "VM" ) {
//				HardModule h = GUIcoder.GetModuleFromMacroFile( OS.ModuleLibPath + "Xhardware" + OS.PATH_S + "power" + OS.PATH_S + "power.B" );
//				int PLanguageIndex = 0;
//				for( int li = 0; li < h.LanguageList.Length; ++li ) {
//					if( h.LanguageList[ li ] == GUISystemData.ModuleLanguage ) {
//						PLanguageIndex = li;
//						break;
//					}
//				}
//				string PNewName = h.NameList[ 2 + PLanguageIndex ];
//				h.isNew = true;
//				h.ignoreHit = true;
//				h.SetUserValue( PNewName, h.LanguageList[ PLanguageIndex ], m.SX - 200, m.SY - 220, 0 );
//				TargetGPanel.myModuleList.Add( h );
//				
//				//预连接电源和控制板
//				try {
//					//m.PORTList[ 44 ].TargetPort = h.PORTList[ 0 ];
//					//m.PORTList[ 45 ].TargetPort = h.PORTList[ 1 ];
//				}
//				catch {
//					
//				}
//			}
		}
		myModuleList.ShowMessage = false;
		
		//更新一下模块资源冲突信息
		RefreshResourceError();
		
		//刷新指令列表
		//GHead.myInsPanel.RefreshInsList();
		
		MyRefresh();
		
		MoveTimer.Enabled = true;
	}
	
	//更新模块资源冲突信息
	public void RefreshResourceError()
	{
		n_GUIcoder.GUIcoder.isAuto = false;
		
		//更新一下模块资源冲突信息
		string s = GUIcoder.VarToText( this );
	}
	
	//闪烁定时器
	void FlashTimerTick( object sender, EventArgs e )
	{
		if( !HaseShow ) {
			return;
		}
		
		if( !TranslateAsked ) {
			TranslateAsked = true;
			
			
			if( n_Language.Language.isEnglish && myModuleList.Language != n_MainSystemData.SystemData.ModuleLanguage ) {
				
				if(MessageBox.Show( "This file was detected as a Chinese program. Do we need to help you translate it into an English program? Note: A small number of programs may make mistakes after translation.",
				                    "Is it translated into English?",
				                    MessageBoxButtons.YesNo ) == DialogResult.Yes ) {
					Translate();
				}
				
			}
		}
		
		Flash = !Flash;
		MyRefresh();
	}
	
	static void SetHotKeyMes()
	{
		n_Debug.Warning.WarningMessage = n_Language.Language.SimShortcutKey;
	}
	
	//按键按下事件
	void UserkeyDown( object sender, KeyEventArgs e )
	{
		if( e.KeyCode == Keys.Delete ) {
			
			if( n_Debug.Debug.Message != null || n_Debug.Warning.ErrMessage != null ) {
				n_Debug.Debug.Message = null;
				n_Debug.Warning.ErrMessage = null;
				return;
			}
			if( SelPanel.ExistSelect ) {
				if( MessageBox.Show( "确定要删除选中的元素吗?", "删除选中元素提示", MessageBoxButtons.OKCancel ) == DialogResult.OK ) {
					SelPanel.DeleteSelect();
				}
			}
		}
		if( e.Modifiers.CompareTo(Keys.Control) == 0 && e.KeyCode == Keys.Y ) {
			if( HideLine == 0 ) {
				HideLine = 1;
			}
			else {
				HideLine = 0;
			}
		}
		if( e.Modifiers.CompareTo(Keys.Control) == 0 && e.KeyCode == Keys.N ) {
			HideName = !HideName;
		}
		if( e.KeyCode == Keys.Space ) {
			
			if( !G.SimulateMode ) {
				
				//判断是否需要调节端口导线颜色
				if( myModuleList.SelectPort != null && !myModuleList.SelectPort.isBus ) {
					
					//if( e.Delta < 0 ) {
						myModuleList.SelectPort.ColorIndex++;
						if( myModuleList.SelectPort.ColorIndex == PortPenList.Number ) {
							myModuleList.SelectPort.ColorIndex = 0;
						}
					//}
					//else {
					//	myModuleList.SelectPort.ColorIndex--;
					//	if( myModuleList.SelectPort.ColorIndex < 0 ) {
					//		myModuleList.SelectPort.ColorIndex = PortPenList.Number - 1;
					//	}
					//}
				}
				else {
					if( n_HardModule.Port.C_Rol == 0 ) {
						n_HardModule.Port.C_Rol = 50;
					}
					else {
						n_HardModule.Port.C_Rol = 0;
						myModuleList.AdjToCross();
					}
					myModuleList.NeedDrawLineMap = true;
				}
			}
			else {
				n_HardModule.HardModule.ShowBigImage = !n_HardModule.HardModule.ShowBigImage;
			}
		}
		if( e.Modifiers.CompareTo(Keys.Shift) == 0 || e.KeyCode == Keys.Escape ) {
			CKeys = e.KeyCode;
			SetHotKeyMes();
		}
		if( e.KeyCode == Keys.ControlKey ) {
			MultSelect = true;
		}
		
		//这里仅用于仿真状态按键控制
		myModuleList.UserKeyDown( e.KeyCode );
		
		
		/*
		if( e.KeyCode == Keys.Escape ) {
			if( n_Debug.Debug.Message != null ) {
				n_Debug.Debug.Message = null;
				MyRefresh();
			}
		}
		*/
		
		int Offx = 0;
		int Offy = 0;
		if( e.KeyCode == Keys.Up ) {
			Offy = -1;
		}
		if( e.KeyCode == Keys.Down ) {
			Offy = 1;
		}
		if( e.KeyCode == Keys.Left ) {
			Offx = -1;
		}
		if( e.KeyCode == Keys.Right ) {
			Offx = 1;
		}
		if( Offx != 0 || Offy != 0 ) {
			foreach( MyObject mo in myModuleList ) {
				if( mo is n_MyFileObject.MyFileObject && mo.isHighLight ) {
			 		mo.SX += Offx;
					mo.SY += Offy;
				}
			}
		}
		MyRefresh();
	}
	
	//按键松开事件
	void UserkeyUp( object sender, KeyEventArgs e )
	{
		if( e.KeyCode == Keys.ShiftKey ) {
			CKeys = Keys.None;
		}
		if( e.KeyCode == Keys.ControlKey ) {
			MultSelect = false;
		}
		
		myModuleList.UserKeyUp( e.KeyCode );
		MyRefresh();
	}
	
	//按键按下事件
	void UserkeyPress( object sender, KeyPressEventArgs e )
	{
		//KeyDownString += e.KeyChar.ToString();
		if( MyControl.FocusObject != null ) {
			
			MyControl.FocusObject.KeyPress( e.KeyChar );
			
			//界面刷新
			MyRefresh();
			e.Handled = true;
		}
	}
	
	//鼠标滚轮事件
	void UserMouseWheel( object sender, MouseEventArgs e )
	{
		if( G.commonEXPBox.ePanel.Visible || MyControl.FocusObject != null ) {
			return;
		}
		bool Moved = n_ModuleLibPanel.MyModuleLibPanel.Scroll( e.X, e.Y, e.Delta>0? 30: -30 );
		
		if( !Moved ) {
			Moved = this.GHead.myInsPanel.Scroll( e.X, e.Y, e.Delta>0? 30: -30 );
			if( !Moved ) {
				Moved = this.GHead.myVarListPanel.Scroll( e.X, e.Y, e.Delta>0? 30: -30 );
			}
			if( !Moved ) {
				
				if( isNoModule ) {
					return;
				}
				
				/*
				//上下移动界面
				//StartX += (eX - Last_mX);
				StartY += e.Delta>0? 70: -70;
				*/
				/*
				//判断是否需要调节端口导线颜色
				if( myModuleList.SelectPort != null && !myModuleList.SelectPort.isBus ) {
					
					if( e.Delta < 0 ) {
						myModuleList.SelectPort.ColorIndex++;
						if( myModuleList.SelectPort.ColorIndex == PortPenList.Number ) {
							myModuleList.SelectPort.ColorIndex = 0;
						}
					}
					else {
						myModuleList.SelectPort.ColorIndex--;
						if( myModuleList.SelectPort.ColorIndex < 0 ) {
							myModuleList.SelectPort.ColorIndex = PortPenList.Number - 1;
						}
					}
				}
				else {*/
					if( e.Delta > 0 ) {
						if( ScaleIndex < ScaleList.Length - 1 ) {
							int mapx = e.X * AScaleMid / AScale - StartX;
							int mapy = e.Y * AScaleMid / AScale - StartY;
							ScaleIndex++;
							AScale = ScaleList[ScaleIndex];
							StartX = e.X * AScaleMid / AScale - mapx;
							StartY = e.Y * AScaleMid / AScale - mapy;
						}
					}
					else {
						if( ScaleIndex > 0 ) {
							int mapx = e.X * AScaleMid / AScale - StartX;
							int mapy = e.Y * AScaleMid / AScale - StartY;
							ScaleIndex--;
							AScale = ScaleList[ScaleIndex];
							StartX = e.X * AScaleMid / AScale - mapx;
							StartY = e.Y * AScaleMid / AScale - mapy;
						}
					}
					myModuleList.NeedDrawLineMap = true;
				}
			//}
		}
		MyRefresh();
	}
	
	//鼠标离开时
	void ImagePanel_MouseLeave( object sender, EventArgs e )
	{
		if( !G.ShowPythonBox ) {
			return;
		}
		RShowX = RHidWidth;
		RisShow = false;
		GHead.RXChanged();
		MyRefresh();
	}
	
	//鼠标进入时
	int EnterTick;
	void ImagePanel_MouseEnter( object sender, EventArgs e )
	{
		SkipRefresh = false;
		
		if( G.ShowPythonBox ) {
			EnterTick = 3;
		}
	}
	
	//界面放缩事件
	void UserScale( int Delta )
	{
		if( Delta < 0 ) {
			if(HardModule.Scale > 0.4f ) {
				HardModule.Scale *= 0.7F;
				if( HardModule.ScaleChanged != null ) {
					HardModule.ScaleChanged();
				}
			}
		}
		else {
			if( HardModule.Scale < 1 ) {
				HardModule.Scale /= 0.7F;
				if( HardModule.ScaleChanged != null ) {
					HardModule.ScaleChanged();
				}
			}
		}
		Invalidate();
	}
	
	//===============================================================================
	
	bool PisInModule;
	
	public int TakeMoIndex;
	public int TakePoIndex;
	public int CLineIndex;
	
	//鼠标双击事件
	void UserMouseDClick( object sender, EventArgs e )
	{
		if( G.SimulateMode ) {
			return;
		}
		if( isNoModule ) {
			return;
		}
		if( myModuleList.SelectPort != null ) {
			DeleteMidPort( myModuleList.SelectPort );
			myModuleList.SelectPort = null;
		}
		else {
			if( PisInModule ) {
				return;
			}
			n_FuncIns.FuncIns funci = new n_FuncIns.FuncIns();
			funci.SetUserValue( GUICommon.SearchName( this ), null, n_Language.Language.ModuleFunc, MouseX, MouseY, 0 );
			funci.isNewTick = n_MyObject.MyObject.MaxNewTick;
			myModuleList.Add( funci );
		}
		//界面刷新
		Invalidate();
	}
	
	//鼠标按下事件
	void UserMouseDown( object sender, MouseEventArgs e )
	{
		try {
		if( !this.Focused ) {
			this.Focus();
		}
		int eX = e.X;
		int eY = e.Y;
		
		//初始悬浮窗口
		if( n_ModuleLibPanel.MyModuleLibPanel.FloatButton ) {
			ShowMessage = false;
			if( SWTip.LeftMouseDown( eX, eY ) ) {
				n_ModuleLibPanel.MyModuleLibPanel.FloatButton = false;
			}
			if( n_ModuleLibPanel.MyModuleLibPanel.FloatButton ) {
				n_ModuleLibPanel.MyModuleLibPanel.FloatButton = false;
				SWTip.CodeButton_MouseDownEvent();
			}
			return;
		}
		//如果显示信息则忽略鼠标按下事件
		if( ShowMessage ) {
			ShowMessage = false;
			return;
		}
		if( G.StartStatus ) {
			G.StartStatus = false;
		}
		if( ePanel.Visible ) {
			ePanel.Visible = false;
			G.commonEXPBox.cExp = null;
			return;
		}
		MoveTick = 0;
		
		if( GUIcoder.AutoMove ) {
			GUIcoder.AutoMove = false;
		}
		//判断是否设置文本信息
		if( MyControl.FocusObject != null ) {
			string name = MyTextBox.Text;
			if( MyControl.FocusObject.Text != name ) {
				MyControl.FocusObject.Text = name;
			}
			MyControl.FocusObject = null;
			ImagePanel.MyTextBox.Visible = false;
			return;
		}
		
		bool CLineDown = false;
		
		//如果按下左键, 传递给组件列表
		if( e.Button == MouseButtons.Left ) {
			
			if( n_Debug.Warning.WarningMessage != null ) {
				n_Debug.Warning.WarningMessage = null;
			}
			if( NewObject != null ) {
				NewObject = null;
			}
			bool isInModule = false;
			
			if( isNoModule ) {
				if( STip.LeftMouseDown( eX, eY ) ) {
					return;
				}
			}
			if( !isInModule ) {
				isInModule = GHead.LeftMouseDown( eX, eY );
			}
			
			if( !G.SimulateMode && !isInModule ) {
				HistoryList_Record();
			}
			if( !isInModule ) {
				isInModule = SelPanel.LeftMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			if( !isInModule && !n_MyPanel.MyPanel.ExistPanel ) {
				isInModule |= myMidPortList.LeftMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			if( !isInModule && !n_MyPanel.MyPanel.ExistPanel ) {
				//这里不应该改变 isInModule, 因为判断连接到模块端口时需要停止导线链, 因而需要调用模块的 MouseDown
				CLineDown = myCLineList.LeftMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			if( !isInModule ) {
				//判断是否是编程导线操作
				if( HideLine == 0 && TakeMoIndex != -1 && TakePoIndex != -1 ) {
					HardModule h = (HardModule)myModuleList.ModuleList[TakeMoIndex];
					
					try {
						Port pp = h.PORTList[TakePoIndex];
					}
					catch {
						MessageBox.Show( TakePoIndex + "," + TakeMoIndex + "," + h.PORTList.Length );
					}
					
					Port p = h.PORTList[TakePoIndex];
					
					AddMidPort( p, eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
					isInModule = true;
					myModuleList.NeedDrawLineMap = true;
				}
			}
			if( !isInModule ) {
				for( int i = 0; i < ObjectMesPanelList.Length; ++i ) {
					isInModule |= ObjectMesPanelList[i].MouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				}
			}
			//if( !isInModule || myMidPortList.MouseOnMidPort != null ) {
			if( !isInModule ) {
				isInModule |= myModuleList.UserMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			isInModule |= CLineDown;
			
			if( !isInModule ) {
				isInModule = mGroupList.MouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			if( !isInModule ) {
				isInModule = EnginePair.UserMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			if( !isInModule ) {
				if( myModuleList.SelectPort != null ) {
					//myModuleList.SelectPort = null;
				}
				else if( myModuleList.SelectIPort != null ) {
					myModuleList.SelectIPort = null;
				}
				else {
					if( SystemData.UIModeSimple ) {
						isMousePress = true;
						Last_mX = eX;
						Last_mY = eY;
					}
					else {
						SelPanel.RightMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
					}
				}
			}
			//这个函数比较占用时间 所以只有点击模块时才需要调用
			if( isInModule && !G.SimulateMode ) {
				TextChangedDetect( null, null );
			}
			PisInModule = isInModule;
			
			//触发文本变化检测
			//ChangeDetectTimer.Enabled = true;
		}
		//判断是否按下右键
		if( e.Button == MouseButtons.Right ) {
			
			if( !SystemData.UIModeSimple ) {
				isMousePress = true;
				Last_mX = eX;
				Last_mY = eY;
			}
			else {
				//清除IPort标志
				if( myModuleList.SelectIPort != null ) {
					myModuleList.SelectIPort = null;
				}
				
				if( myModuleList.SelectPort != null ) {
					//DeleteMidPort( myModuleList.SelectPort );
					myModuleList.SelectPort = null;
				}
				//判断是否是编程导线操作
				else if( TakeMoIndex != -1 && TakePoIndex != -1 ) {
					
					if( !G.SimulateMode ) {
						HardModule h = (HardModule)myModuleList.ModuleList[TakeMoIndex];
						try {
							Port pp = h.PORTList[TakePoIndex];
						}
						catch {
							MessageBox.Show( TakePoIndex + "," + TakeMoIndex + "," + h.PORTList.Length );
						}
						Port p = h.PORTList[TakePoIndex];
						DeleteMidPort( p );
						p.TargetPort = null;
						RefreshLinePortName();
					}
				}
				//判断是否是电路导线操作
				else if( CLineIndex != -1 ) {
					if( !G.SimulateMode ) {
						myCLineList.Delete( CLineIndex );
						G.CGPanel.CLineIndex = -1;
						myModuleList.NeedDrawLineMap = true;
					}
				}
				else {
					bool del0 = myCLineList.RightMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
					
					bool del = myMidPortList.RightMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
					if( del ) {
						myModuleList.NeedDrawLineMap = true;
					}
					else {
						SelPanel.RightMouseDown( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
					}
				}
			}
		}
		//判断是否按下鼠标中键
		if( e.Button == MouseButtons.Middle ) {
			int mapx = e.X * AScaleMid / AScale - StartX;
			int mapy = e.Y * AScaleMid / AScale - StartY;
			ScaleIndex = 10;
			AScale = ScaleList[ScaleIndex];
			StartX = e.X * AScaleMid / AScale - mapx;
			StartY = e.Y * AScaleMid / AScale - mapy;
			
			isMousePress = true;
			Last_mX = eX;
			Last_mY = eY;
			
			myModuleList.NeedDrawLineMap = true;
		}
		}
		catch( Exception ee ) {
			MessageBox.Show( "遇到了一个问题, 建议尽快把程序保存并尝试重新运行软件. 请把如下报错信息反馈给开发团队 910360201@qq.com, 谢谢!\n"
			                 + ee.ToString(), "出错提示" );
		}
		//界面刷新
		MyRefresh();
	}
	
	//鼠标松开事件
	void UserMouseUp( object sender, MouseEventArgs em )
	{
		try {
		MultEageShow = false;
		
		if( ePanel.Visible ) {
			return;
		}
		
		int eX = em.X;
		int eY = em.Y;
		
		if( em.Button == MouseButtons.Left ) {
			
			//注意这里 GHead需要排在myModuleList之后, 因为在GHead中可能添加新的流程指令, 不希望它紧接着响应MouseUp事件
			myModuleList.UserMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			mGroupList.MouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			
			if( isNoModule ) {
				STip.LeftMouseUp( eX, eY );
			}
			SWTip.LeftMouseUp( eX, eY );
			
			GHead.LeftMouseUp( eX, eY );
			
			if( !n_MyPanel.MyPanel.ExistPanel ) {
				myMidPortList.LeftMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				myCLineList.LeftMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			
			SelPanel.LeftMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			/*
			if( SystemData.UIModeSimple ) {
				SelPanel.LeftMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				SelPanel.RightMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			*/
			EnginePair.UserMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			
			if( !G.SimulateMode ) {
				TextChangedDetect( null, null );
			}
			isMousePress = false;
			myModuleList.NeedDrawLineMap = true;
		}
		if( em.Button == MouseButtons.Right ) {
			
			//右键松开时显示菜单页面
			//if( !G.SimulateMode && myModuleList.MouseOnObject != null ) {
			//	if( !myModuleList.MouseOnObject.IgnoreHighLight ) {
			//		myModuleList.MouseOnObject.isHighLight = true;
			//	}
			//}
			
			
			SelPanel.RightMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			/*
			if( SystemData.UIModeSimple ) {
				SelPanel.LeftMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				SelPanel.RightMouseUp( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			*/
			if( isMousePress ) {
				isMousePress = false;
//				if( n_GUIset.GUIset.isDefault && MoveTick < MaxMoveTick ) {
//					n_FuncIns.FuncIns funci = new n_FuncIns.FuncIns();
//					funci.SetUserValue( GUICommon.SearchName( G.CGPanel ), "?void", 0, 0, 0 );
//					funci.isNew = true;
//					myModuleList.Add( funci );
//				}
			}
			
			//isMousePress = false;
		}
		if( em.Button == MouseButtons.Middle ) {
			isMousePress = false;
		}
		
		//G.CGPanel.myRecycler.Visible = false;
		
		}
		catch( Exception ee ) {
			MessageBox.Show( "遇到了一个问题, 建议尽快把程序保存并尝试重新运行软件. 请把如下报错信息反馈给开发团队 910360201@qq.com, 谢谢!\n"
			                 + ee.ToString(), "出错提示" );
		}
		//界面刷新
		MyRefresh();
	}
	
	//鼠标移动事件
	void UserMouseMove( object sender, MouseEventArgs em )
	{
		if( ePanel.Visible ) {
			return;
		}
		int eX = em.X;
		int eY = em.Y;
		
		if( ShowMessage ) {
			if( n_ModuleLibPanel.MyModuleLibPanel.FloatButton ) {
				SWTip.MouseMove( eX, eY );
				MyRefresh();
			}
			return;
		}
		MoveTick++;
		
		MouseX = eX;
		MouseY = eY;
		
		//左边栏调整
		if( n_Head.Head.HeadShow ) {
			if( MouseX >= n_Head.Head.HeadWidth ) {
				if( !n_ModuleLibPanel.ModuleDetail.ShowDetail ) {
					n_Head.Head.HeadShow = false;
					n_Head.Head.ShowX = -( n_Head.Head.HeadWidth - n_Head.Head.HidWidth );
				}
			}
		}
		else {
			if( MouseX < n_Head.Head.HidWidth ) {
				n_Head.Head.HeadShow = true;
				n_Head.Head.ShowX = 0;
			}
		}
		//右边栏调整
		if( RisShow ) {
			if( MouseX < Width - MaxRShowX ) {
				RShowX = RHidWidth;
				RisShow = false;
			}
		}
		else {
			if( MouseX >= Width - RHidWidth ) {
				if( EnterTick == 0 ) {
					RShowX = MaxRShowX;
					RisShow = true;
				}
			}
			else {
				if( EnterTick > 0 ) {
					EnterTick--;
				}
			}
		}
		
		//更新拾取对象
		TakeMoIndex = -1;
		TakePoIndex = -1;
		CLineIndex = -1;
		
		if( HideLine == 0 && !n_MyPanel.MyPanel.ExistPanel && !isMousePress && eX >= 0 && eX < LineMap.Width && eY >= 0 && eY < LineMap.Height ) {
			Color c = LineMap.GetPixel( eX, eY );
			
			if( c.R != 255 || c.G != 255 || c.B != 255 ) {
				if( c.B / 16 == 0 ) {
					TakeMoIndex = (c.B % 16) * 256 + c.R;
					TakePoIndex = c.G;
				}
				else {
					CLineIndex = c.G * 256 + c.R;
				}
			}
		}
		
		//处理背景的拖动
		if( isMousePress ) {
			
			float x = (eX - Last_mX) * 1024f / AScale + modX;
			float y = (eY - Last_mY) * 1024f / AScale + modY;
			StartX += (int)x;
			StartY += (int)y;
			modX = x - (int)x;
			modY = y - (int)y;
			
			Last_mX = eX;
			Last_mY = eY;
		}
		//界面刷新
		if( MyControl.FocusObject == null ) {
			
			if( isNoModule ) {
				STip.MouseMove( eX, eY );
			}
			
			bool MouseOn = GHead.MouseMove( eX, eY );
			
			bool temp = myRecycler.MouseMove( eX, eY );
			
			if( !n_MyPanel.MyPanel.ExistPanel ) {
				myMidPortList.MouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				myCLineList.MouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			
			if( !MouseOn ) {
				
				myModuleList.UserMouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				myModuleList.RefreshGroup( mGroupList );
				
				mGroupList.MouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
				
				SelPanel.MouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
			}
			
			EnginePair.UserMouseMove( eX * AScaleMid / AScale - StartX, eY * AScaleMid / AScale - StartY );
		}
		
		if( !GHead.isCompile && !GHead.isDownLoad ) {
			MyRefresh();
		}
	}
	
	void ImagePanel_SizeChanged( object sender, EventArgs e )
	{
		float x = (Width - OldW) / 2 * 1024f / AScale;
		float y = (Height - OldH) / 2 * 1024f / AScale;
		StartX += (int)x;
		StartY += (int)y;
		
		OldW = Width;
		OldH = Height;
	}
	
	//===============================================================================
	
	//取消当前连接
	void DeleteMidPort( Port p )
	{
		if( p.MidPortIndex != -1 ) {
			myMidPortList.Delete( p.MidPortIndex );
			p.MidPortIndex = -1;
		}
	}
	
	void AddMidPort( Port p, int x, int y )
	{
		if( p.MidPortIndex == -1 ) {
			p.MidPortIndex = myMidPortList.AddList();
		}
		
		
		
		//防护!!!!
		myMidPortList.SetPort( p.MidPortIndex, p, p.TargetPort );
		
		
		
		if( !myMidPortList.Add( p.MidPortIndex, x, y ) ) {
			p.MidPortIndex = -1;
		}
	}
	
	//-------------------------------------------------------
	
	//记录当前点
	public void HistoryList_Record()
	{
		string NewCode = VarToText();
		if( UndoNext != UndoStart ) {
			int t = UndoNext - 1;
			if( t < 0 ) {
				t = HistoryList.Length - 1;
			}
			if( HistoryList[t] == NewCode ) {
				return;
			}
		}
		if( UndoNext != UndoEnd ) {
			if( HistoryList[UndoNext] == NewCode ) {
				return;
			}
		}
		HistoryList[UndoNext] = NewCode;
		HistoryPointList[UndoNext] = new Point( StartX, StartY );
		HistoryScaleList[UndoNext] = AScale;
		
		++UndoNext;
		if( UndoNext == HistoryList.Length ) {
			UndoNext = 0;
		}
		UndoEnd = UndoNext;
		
		if( UndoStart == UndoNext ) {
			UndoStart++;
			if( UndoStart == HistoryList.Length ) {
				UndoStart = 0;
			}
		}
		HistoryList_RefreshMessage();
	}
	
	//撤销
	public void HistoryList_Undo()
	{
		//第一次撤销时, 需要保存当前的页面
		if( UndoNext == UndoEnd ) {
			HistoryList[UndoNext] = VarToText();
			HistoryPointList[UndoNext] = new Point( StartX, StartY );
			HistoryScaleList[UndoNext] = AScale;
		}
		
		if( UndoNext != UndoStart ) {
			UndoNext--;
			if( UndoNext < 0 ) {
				UndoNext = HistoryList.Length - 1;
			}
			LoadModule( HistoryList[UndoNext], false );
			StartX = HistoryPointList[UndoNext].X;
			StartY = HistoryPointList[UndoNext].Y;
			AScale = HistoryScaleList[UndoNext];
			HistoryList_RefreshMessage();
		}
	}
	
	//重做
	public void HistoryList_Redo()
	{
		if( UndoNext != UndoEnd ) {
			UndoNext++;
			if( UndoNext == HistoryList.Length ) {
				UndoNext = 0;
			}
			LoadModule( HistoryList[UndoNext], false );
			StartX = HistoryPointList[UndoNext].X;
			StartY = HistoryPointList[UndoNext].Y;
			AScale = HistoryScaleList[UndoNext];
			HistoryList_RefreshMessage();
		}
	}
	
	int UndoNumber;
	int RedoNumber;
	
	//更新操作步数信息
	void HistoryList_RefreshMessage()
	{
		UndoNumber = UndoNext - UndoStart;
		RedoNumber = UndoEnd - UndoNext;
		UndoNumber = UndoNumber < 0? UndoNumber + HistoryList.Length: UndoNumber;
		RedoNumber = RedoNumber < 0? RedoNumber + HistoryList.Length: RedoNumber;
		GHead.UndoButton.TipText = n_Language.Language.UndoTip1 + " " + UndoNumber + " " + n_Language.Language.UndoTip2;
		GHead.RedoButton.TipText = n_Language.Language.RedoTip1 + " " + RedoNumber + " " + n_Language.Language.RedoTip2;
	}
}
}


